少提交了一个文件

This commit is contained in:
游由 2022-02-18 16:59:04 +08:00
parent 63b0036263
commit 2d5172de39
1 changed files with 0 additions and 576 deletions

View File

@ -202,67 +202,6 @@ impl Solution {
numbers
}
/// 20.有效的括号
///
/// [原题链接](https://leetcode-cn.com/problems/valid-parentheses/)
pub fn is_valid(s: String) -> bool {
let mut v = vec![];
for c in s.chars() {
match c as char {
'(' | '[' | '{' => v.push(c),
')' => {
match v.last() {
None => return false,
Some(s) => {
if *s == '(' {
v.pop();
} else {
return false;
}
}
}
}
']' => {
match v.last() {
None => return false,
Some(s) => {
if *s == '[' {
v.pop();
} else {
return false;
}
}
}
}
'}' => {
match v.last() {
None => return false,
Some(s) => {
if *s == '{' {
v.pop();
} else {
return false;
}
}
}
}
_ => (),
}
}
v.is_empty()
}
/// 104.二叉树的最大深度
///
/// [原题链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if let Some(node) = root {
1 + std::cmp::max(Self::max_depth(node.borrow().left.clone()), Self::max_depth(node.borrow().right.clone()))
} else {
0
}
}
/// 343.整数拆分
///
/// [原题链接](https://leetcode-cn.com/problems/integer-break/)
@ -278,17 +217,6 @@ impl Solution {
}
}
/// 169.多数元素
///
/// [原题链接](https://leetcode-cn.com/problems/majority-element/)
pub fn majority_element(nums: Vec<i32>) -> i32 {
nums.iter().fold((0, -1), |mut acc, &num| {
if acc.0 == 0 { acc.1 = num }
acc.0 += if acc.1 == num { 1 } else { -1 };
acc
}).1
}
/// 1404.将二进制表示减到 1 的步骤数
///
/// [原题链接](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/)
@ -382,28 +310,6 @@ impl Solution {
idx
}
/// 171.Excel表列序号
///
/// [原题链接](https://leetcode-cn.com/problems/excel-sheet-column-number/)
pub fn title_to_number(s: String) -> i32 {
s.chars().fold(0, |col, c| col * 26 + c as i32 - 64)
}
/// 168.Excel表列名称
///
/// [原题链接](https://leetcode-cn.com/problems/excel-sheet-column-title/)
pub fn convert_to_title(n: i32) -> String {
let mut s = String::with_capacity(8);
let mut n = n;
while n != 0 {
let c = (((n - 1) % 26) as u8 + b'A') as char;
s.insert(0, c);
n = (n - 1) / 26;
}
s
}
/// 415.字符串相加
///
/// [原题链接](https://leetcode-cn.com/problems/add-strings/)
@ -421,21 +327,6 @@ impl Solution {
res
}
/// 78.子集
///
/// [原题链接](https://leetcode-cn.com/problems/subsets/)
pub fn subsets(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut ret = vec![vec![]];
for num in nums {
let mut temp = ret.clone();
temp.iter_mut().for_each(|x| x.push(num));
ret.append(&mut temp);
}
ret
}
/// 面试题 16.07.最大数值
///
/// [原题链接](https://leetcode-cn.com/problems/maximum-lcci/)
@ -578,30 +469,6 @@ impl Solution {
solutions
}
/// 36.有效的数独
///
/// [原题链接](https://leetcode-cn.com/problems/valid-sudoku/)
pub fn is_valid_sudoku(board: Vec<Vec<char>>) -> bool {
let mut row_lookup = [[false; 9]; 9];
let mut col_lookup = [[false; 9]; 9];
let mut sub_lookup = [[false; 9]; 9];
for row in 0..9 {
for col in 0..9 {
if board[row][col] == '.' { continue; }
let idx = board[row][col] as usize - '1' as usize;
let sub_idx = ((row / 3) * 3 + col / 3) as usize;
if row_lookup[row][idx] || col_lookup[col][idx] || sub_lookup[sub_idx][idx] {
return false;
} else {
row_lookup[row][idx] = true;
col_lookup[col][idx] = true;
sub_lookup[sub_idx][idx] = true;
}
}
}
return true;
}
/// 188.买卖股票的最佳时机 IV
///
/// [原题链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/)
@ -671,97 +538,6 @@ impl Solution {
false
}
/// 48.旋转图像
///
/// [原题链接](https://leetcode-cn.com/problems/rotate-image/)
/// # 方法1 新矩阵旋转行
/// ```rust
/// pub fn rotate1(matrix: &mut Vec<Vec<i32>>) {
/// let n = matrix.len();
/// let mut matrix_new = matrix.clone();
/// for i in 0..n {
/// for j in 0..n {
/// matrix_new[j][n - i - 1] = matrix[i][j];
/// }
/// }
/// *matrix = matrix_new;
/// }
/// ```
/// # 方法2 原地旋转 分块
/// ```rust
/// pub fn rotate1(matrix: &mut Vec<Vec<i32>>) {
/// let n = matrix.len();
/// for i in 0..n / 2 {
/// for j in 0..(n + 1) / 2 {
/// let temp = 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] = temp;
/// }
/// }
/// }
/// ```
/// # 方法3 翻转代替旋转
///
pub fn rotate1(matrix: &mut Vec<Vec<i32>>) {
let n = matrix.len();
for i in 0..n / 2 {
for j in 0..n {
matrix[i][j] ^= matrix[n - i - 1][j];
matrix[n - i - 1][j] ^= matrix[i][j];
matrix[i][j] ^= matrix[n - i - 1][j];
}
}
for i in 0..n {
for j in 0..i {
matrix[i][j] ^= matrix[j][i];
matrix[j][i] ^= matrix[i][j];
matrix[i][j] ^= matrix[j][i];
}
}
}
/// 125.验证回文串
///
/// [原题链接](https://leetcode-cn.com/problems/valid-palindrome/)
/// # 方法1 双指针
/// 头尾双指针遍历
/// ## 源码
/// ```rust
/// pub fn is_palindrome1(s: String) -> bool {
/// if s.len() <= 1 {
/// return true;
/// }
/// let s = s.into_bytes();
/// let (mut i, mut j) = (0usize, s.len() - 1);
/// while i < j {
/// while i < j && !s[i].is_ascii_alphanumeric() {
/// i += 1;
/// }
/// while i < j && !s[j].is_ascii_alphanumeric() {
/// j -= 1;
/// }
/// if i < j {
/// if s[i].to_ascii_lowercase() != s[j].to_ascii_lowercase() {
/// return false;
/// }
/// i += 1;
/// j -= 1;
/// }
/// }
/// true
/// }
/// ```
/// # 方法2 筛选
/// 实现见源码
pub fn is_palindrome1(s: String) -> bool {
let a = s.to_ascii_lowercase().into_bytes().into_iter().filter(|c| c.is_ascii_alphanumeric()).collect::<Vec<u8>>();
let mut b = a.clone();
b.reverse();
a == b
}
/// 435.无重叠区间
///
/// [原题链接](https://leetcode-cn.com/problems/non-overlapping-intervals/)
@ -783,32 +559,6 @@ impl Solution {
count
}
/// 67.二进制求和
///
/// [原题链接](https://leetcode-cn.com/problems/add-binary/)
pub fn add_binary(mut a: String, mut b: String) -> String {
let mut carry = 0;
let mut res = String::new();
loop {
let (n1, n2) = (a.pop(), b.pop());
if n1 == None && n2 == None { break; }
let mut sum = carry;
if let Some(x) = n1 {
sum += x.to_digit(2).unwrap();
}
if let Some(x) = n2 {
sum += x.to_digit(2).unwrap();
}
carry = sum / 2;
res.insert_str(0, &(sum % 2).to_string());
}
if carry > 0 { res.insert_str(0, &carry.to_string()); }
res
}
/// 1342.将数字变成 0 的操作次数
///
/// [原题链接](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero/)
@ -1202,28 +952,6 @@ impl Solution {
}
}
/// 86.分隔链表
///
/// [原题链接](https://leetcode-cn.com/problems/partition-list/)
pub fn partition(mut head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> {
let mut less_than_x_head = None;
let mut less_than_x = &mut less_than_x_head;
let mut greater_than_x_head = None;
let mut greater_than_x = &mut greater_than_x_head;
while let Some(mut box_node) = head {
head = box_node.next.take();
if box_node.val < x {
*less_than_x = Some(box_node);
less_than_x = &mut less_than_x.as_mut()?.next;
} else {
*greater_than_x = Some(box_node);
greater_than_x = &mut greater_than_x.as_mut()?.next;
}
}
*less_than_x = greater_than_x_head;
less_than_x_head
}
/// 239.滑动窗口最大值
///
/// [原题链接](https://leetcode-cn.com/problems/sliding-window-maximum/)
@ -1466,165 +1194,6 @@ impl Solution {
ans
}
/// 14.最长公共前缀
///
/// [原题链接](https://leetcode-cn.com/problems/longest-common-prefix/)
/// # 方法1 排序
/// 排序后,返回第一个和最后一个的公共前缀
/// ##源码
/// ```rust
/// pub fn longest_common_prefix(mut strs: Vec<String>) -> String {
/// if strs.is_empty() {
/// return "".to_string();
/// }
/// strs.sort();
/// let first = strs.first().unwrap().as_bytes();
/// let last = strs.last().unwrap().as_bytes();
/// let n = std::cmp::min(first.len(), last.len());
/// let mut ret = String::with_capacity(n);
/// for i in 0..n {
/// if first[i] != last[i] {
/// break;
/// }
/// ret.push(first[i] as char);
/// }
/// ret
/// }
/// ```
/// # 方法2 横向扫描
/// 每两个之间的公共前缀。
/// ## 源码
/// ```rust
/// pub fn longest_common_prefix(mut strs: Vec<String>) -> String {
/// fn lcp(str1: &String, str2: &String) -> String {
/// let n = std::cmp::min(str1.len(), str2.len());
/// let b1 = str1.as_bytes();
/// let b2 = str2.as_bytes();
/// let mut ret = String::new();
/// for i in 0..n {
/// if b1[i] != b2[i] {
/// break;
/// }
/// ret.push(b1[i] as char);
/// }
/// ret
/// }
/// if strs.is_empty() {
/// return "".to_string();
/// }
/// let mut prefix = strs[0].clone();
/// for i in 1..strs.len() {
/// prefix = lcp(&prefix, &strs[i]);
/// if prefix.is_empty() {
/// break;
/// }
/// }
/// prefix
/// }
/// ```
/// # 方法3 纵向扫描
/// 从0开始每个字符是否相等。
/// ## 源码
/// ```rust
/// pub fn longest_common_prefix(strs: Vec<String>) -> String {
/// if strs.is_empty() {
/// return "".to_string();
/// }
/// let length = strs[0].len();
/// let count = strs.len();
/// for i in 0..length {
/// let b = strs[0].as_bytes()[i];
/// for j in 1..count {
/// if i == strs[j].len() || strs[j].as_bytes()[i] != b {
/// return strs[0].split_at(i).0.clone().to_string();
/// }
/// }
/// }
/// return strs[0].clone();
/// }
/// ```
/// # 方法4 分治
/// 两两之间的公共前缀。
/// ## 源码
/// ```rust
/// pub fn longest_common_prefix(strs: Vec<String>) -> String {
/// fn lcp(str1: &String, str2: &String) -> String {
/// let n = std::cmp::min(str1.len(), str2.len());
/// let b1 = str1.as_bytes();
/// let b2 = str2.as_bytes();
/// let mut ret = String::new();
/// for i in 0..n {
/// if b1[i] != b2[i] {
/// break;
/// }
/// ret.push(b1[i] as char);
/// }
/// ret
/// }
/// fn lcp_r(strs: &Vec<String>, start: usize, end: usize) -> String {
/// if start == end {
/// strs[start].clone()
/// } else {
/// let mid = (end - start) / 2 + start;
/// let lcp_left = lcp_r(strs, start, mid);
/// let lcp_right = lcp_r(strs, mid + 1, end);
/// lcp(&lcp_left, &lcp_right)
/// }
/// }
/// if strs.is_empty() {
/// "".to_string()
/// } else {
/// lcp_r(&strs, 0, strs.len() - 1).to_owned()
/// }
/// }
/// ```
/// # 方法5 二分查找
/// # 方法6 字典树
pub fn longest_common_prefix(strs: Vec<String>) -> String {
if strs.is_empty() {
return "".to_string();
}
let length = strs[0].len();
let count = strs.len();
for i in 0..length {
let b = strs[0].as_bytes()[i];
for j in 1..count {
if i == strs[j].len() || strs[j].as_bytes()[i] != b {
return strs[0].split_at(i).0.clone().to_string();
}
}
}
return strs[0].clone();
}
/// 66.加一
///
/// [原题链接](https://leetcode-cn.com/problems/plus-one/)
pub fn plus_one(mut digits: Vec<i32>) -> Vec<i32> {
for i in (0..digits.len()).rev() {
digits[i] += 1;
digits[i] = digits[i] % 10;
if digits[i] != 0 {
return digits;
}
}
let mut ret = vec![1];
ret.extend(digits);
ret
}
/// 172.阶乘后的零
///
/// [原题链接](https://leetcode-cn.com/problems/factorial-trailing-zeroes/)
pub fn trailing_zeroes(mut n: i32) -> i32 {
let mut zero_count = 0;
while n > 0 {
n /= 5;
zero_count += n;
}
zero_count
}
/// 684.冗余连接
///
/// [原题链接](https://leetcode-cn.com/problems/redundant-connection/)
@ -1656,63 +1225,6 @@ impl Solution {
Vec::<i32>::new()
}
/// 58.最后一个单词的长度
///
/// [原题链接](https://leetcode-cn.com/problems/length-of-last-word/)
/// # 方法1 反向遍历
/// 实现见源码
/// # 方法2 分割字符串
/// 先删除尾部的无效字符,按空格分割字符串,去最后一个,返回其长度。
/// ## 源码
/// ```rust
/// pub fn length_of_last_word(s: String) -> i32 {
/// s.trim_end().split_whitespace().last().unwrap_or("").len() as i32
/// }
/// ```
pub fn length_of_last_word(s: String) -> i32 {
let mut ret = 0;
let s = s.into_bytes();
let mut is_last_word = false;
for &c in s.iter().rev() {
if c != b' ' {
is_last_word = true;
}
if is_last_word {
if c == b' ' {
is_last_word = false;
break;
}
ret += 1;
}
}
ret
}
/// 88.合并两个有序数组
///
/// [原题链接](https://leetcode-cn.com/problems/merge-sorted-array/)
pub fn merge(nums1: &mut Vec<i32>, m: i32, nums2: &mut Vec<i32>, n: i32) {
/*nums1.resize(m as usize, 0);
nums1.extend(nums2.clone());
nums1.sort();*/
let mut p1 = m - 1;
let mut p2 = n - 1;
let mut p = m + n - 1;
while p1 >= 0 && p2 >= 0 {
if nums1[p1 as usize] < nums2[p2 as usize] {
nums1[p as usize] = nums2[p2 as usize];
p2 -= 1;
} else {
nums1[p as usize] = nums1[p1 as usize];
p1 -= 1;
}
p -= 1;
}
for i in 0..((p2 + 1) as usize) {
nums1[i] = nums2[i];
}
}
/// 1018.可被5整除的二进制前缀
///
/// [原题链接](https://leetcode-cn.com/problems/binary-prefix-divisible-by-5/)
@ -1726,45 +1238,6 @@ impl Solution {
ret
}
/// 29.两数相除
///
/// [原题链接](https://leetcode-cn.com/problems/divide-two-integers/)
/// # 方法1 内置API
/// ```rust
/// pub fn divide(dividend: i32, divisor: i32) -> i32 {
/// use std::ops::Div;
/// if divisor == 0 {
/// return 0;
/// } else if divisor == -1 && dividend == i32::MIN {
/// return i32::MAX;
/// }
/// dividend.div(divisor)
/// }
/// ```
/// # 方法2 位运算除法
pub fn divide(dividend: i32, divisor: i32) -> i32 {
if divisor == 0 {
return 0;
} else if divisor == -1 && dividend == i32::MIN {
return i32::MAX;
}
let negative = (dividend ^ divisor) < 0;
let mut t = (dividend as i64).abs();
let mut d = (divisor as i64).abs();
let mut ret = 0;
for i in (0..32).rev() {
if (t >> i) >= d {
ret |= 1 << i;
t -= d << i;
}
}
if negative {
-ret
} else {
ret
}
}
/// 947.移除最多的同行或同列石头
///
/// [原题链接](https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column/)
@ -1800,38 +1273,6 @@ impl Solution {
(stones.len() - count) as i32
}
/// 11.盛最多水的容器
///
/// [原题链接](https://leetcode-cn.com/problems/container-with-most-water/)
/// # 方法1 暴力模拟
/// ## 源码
/// ```rust
/// pub fn max_area(height: Vec<i32>) -> i32 {
/// let mut area = 0;
/// for i in 0..height.len() {
/// for j in (i + 1)..height.len() {
/// area = area.max((j - i) as i32 * height[i].min(height[j]));
/// }
/// }
/// area
/// }
/// ```
/// # 方法2 双指针
/// 每次淘汰掉双指针最小的那个数。实现见源码
pub fn max_area(height: Vec<i32>) -> i32 {
let (mut l, mut r) = (0, height.len() - 1);
let mut area = 0;
while l < r {
area = area.max((r - l) as i32 * height[l].min(height[r]));
if height[l] <= height[r] {
l += 1;
} else {
r -= 1;
}
}
area
}
/// 287.寻找重复数
///
/// [原题链接](https://leetcode-cn.com/problems/find-the-duplicate-number/)
@ -3129,14 +2570,6 @@ mod tests {
assert_eq!(i, 0);
}
#[test]
fn test_title_to_number() {
let t = "AA".to_string();
let number = Solution::title_to_number(t);
//println!("{}", number);
assert_eq!(number, 27i32);
}
#[test]
fn test_find_redundant_connection() {
let edges = vec![vec![1, 2], vec![2, 3], vec![3, 4], vec![1, 4], vec![1, 5]];
@ -3153,15 +2586,6 @@ mod tests {
assert_eq!(by5, vec![true, false, false, false, true, false, false, true, true]);
}
#[test]
fn test_divide() {
let dividend = i32::MIN;
let divisor = -1;
let d = Solution::divide(dividend, divisor);
//println!("{}", d);
assert_eq!(d, i32::MAX);
}
#[test]
fn test_remove_stones() {
let stones = vec![vec![0, 0], vec![0, 1], vec![1, 0], vec![1, 2], vec![2, 1], vec![2, 2]];