Skip to content

Commit ef0f53d

Browse files
committed
Add more solutions
1 parent a742ab5 commit ef0f53d

12 files changed

+374
-1
lines changed

README.md

+13-1
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use std::collections::HashMap;
2+
3+
// 387. First Unique Character in a String, Easy
4+
// https://leetcode.com/problems/first-unique-character-in-a-string/
5+
impl Solution {
6+
pub fn first_uniq_char(s: String) -> i32 {
7+
let mut map = HashMap::<char, i32>::new();
8+
9+
for char in s.chars() {
10+
map.entry(char).and_modify(|f| *f += 1).or_insert(1);
11+
}
12+
13+
for (i, char) in s.chars().enumerate() {
14+
if *map.get(&char).unwrap() == 1 {
15+
return i as i32;
16+
}
17+
}
18+
19+
-1
20+
}
21+
}
22+
23+
struct Solution {}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// 33. Search in Rotated Sorted Array, Medium
2+
// https://leetcode.com/problems/search-in-rotated-sorted-array/
3+
impl Solution {
4+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
5+
let mut nums = nums.iter().enumerate().map(|(i, n)| (*n, i)).collect::<Vec<(i32, usize)>>();
6+
nums.sort_unstable();
7+
8+
let i = nums.binary_search_by(|p| p.0.cmp(&target));
9+
match i {
10+
Ok(i) => return nums[i].1 as i32,
11+
Err(_) => return -1,
12+
}
13+
}
14+
}
15+
16+
struct Solution {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Definition for a binary tree node.
2+
#[derive(Debug, PartialEq, Eq)]
3+
pub struct TreeNode {
4+
pub val: i32,
5+
pub left: Option<Rc<RefCell<TreeNode>>>,
6+
pub right: Option<Rc<RefCell<TreeNode>>>,
7+
}
8+
9+
impl TreeNode {
10+
#[inline]
11+
pub fn new(val: i32) -> Self {
12+
TreeNode { val, left: None, right: None }
13+
}
14+
}
15+
16+
use std::cell::RefCell;
17+
use std::rc::Rc;
18+
19+
// 1315. Sum of Nodes with Even-Valued Grandparent, Medium
20+
// https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/
21+
impl Solution {
22+
pub fn sum_even_grandparent(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
23+
fn bfs(node: Option<Rc<RefCell<TreeNode>>>, parent_val: i32, grand_parent_val: i32, ans: &mut i32) {
24+
if node.is_some() {
25+
let node = node.as_ref().unwrap().borrow();
26+
27+
if grand_parent_val != -1 && grand_parent_val % 2 == 0 {
28+
*ans += node.val;
29+
}
30+
31+
bfs(node.left.clone(), node.val, parent_val, ans);
32+
bfs(node.left.clone(), node.val, parent_val, ans);
33+
}
34+
}
35+
36+
let mut ans = 0;
37+
38+
bfs(root, -1, -1, &mut ans);
39+
ans
40+
}
41+
}
42+
43+
struct Solution {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Definition for a binary tree node.
2+
#[derive(Debug, PartialEq, Eq)]
3+
pub struct TreeNode {
4+
pub val: i32,
5+
pub left: Option<Rc<RefCell<TreeNode>>>,
6+
pub right: Option<Rc<RefCell<TreeNode>>>,
7+
}
8+
9+
impl TreeNode {
10+
#[inline]
11+
pub fn new(val: i32) -> Self {
12+
TreeNode { val, left: None, right: None }
13+
}
14+
}
15+
16+
use std::cell::RefCell;
17+
use std::rc::Rc;
18+
19+
// 543. Diameter of Binary Tree, Easy
20+
// https://leetcode.com/problems/diameter-of-binary-tree/
21+
impl Solution {
22+
pub fn diameter_of_binary_tree(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
23+
fn bfs(node: Option<Rc<RefCell<TreeNode>>>, max_path_length: &mut i32) -> i32 {
24+
if node.is_none() {
25+
return 0;
26+
}
27+
let node = node.as_ref().unwrap().borrow();
28+
29+
let path_left = bfs(node.left.clone(), max_path_length);
30+
let path_right = bfs(node.right.clone(), max_path_length);
31+
32+
let path_length = 1 + path_left + path_right;
33+
*max_path_length = i32::max(*max_path_length, path_length);
34+
35+
return 1 + i32::max(path_left, path_right);
36+
}
37+
38+
let mut max_path_length = 0;
39+
bfs(root, &mut max_path_length);
40+
41+
max_path_length - 1
42+
}
43+
}
44+
45+
struct Solution {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// 34. Find First and Last Position of Element in Sorted Array, Medium
2+
// https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
3+
impl Solution {
4+
pub fn search_range(nums: Vec<i32>, target: i32) -> Vec<i32> {
5+
let mut ans = vec![];
6+
7+
match nums.binary_search(&target) {
8+
Ok(pos) => {
9+
let mut i = pos;
10+
let mut j = pos;
11+
while i > 0 && nums[i] == target {
12+
i -= 1;
13+
}
14+
while j < nums.len() - 1 && nums[i] == target {
15+
j += 1;
16+
}
17+
ans.append(&mut vec![i as i32 + 1, j as i32 - 1]);
18+
}
19+
Err(_) => ans.append(&mut vec![-1, -1]),
20+
}
21+
22+
ans
23+
}
24+
}
25+
26+
struct Solution {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use std::collections::HashMap;
2+
3+
// 1481. Least Number of Unique Integers after K Removals, Medium
4+
// https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/
5+
impl Solution {
6+
pub fn find_least_num_of_unique_ints(arr: Vec<i32>, k: i32) -> i32 {
7+
let mut dict = HashMap::<i32, i32>::new();
8+
9+
for num in arr.iter() {
10+
dict.entry(*num).and_modify(|n| *n += 1).or_insert(1);
11+
}
12+
13+
let mut list = dict.keys().map(|k| (*k, dict[k])).collect::<Vec<(i32, i32)>>();
14+
list.sort_unstable_by(|a, b| a.1.cmp(&b.1));
15+
16+
let mut k = k;
17+
let mut i = 0;
18+
let mut num_uniques = list.len();
19+
20+
while k > 0 {
21+
let can_rm = i32::min(k, list[i].1);
22+
23+
if list[i].1 - can_rm == 0 {
24+
num_uniques -= 1;
25+
i += 1;
26+
k -= can_rm;
27+
} else {
28+
k -= can_rm;
29+
}
30+
}
31+
32+
// let list =
33+
34+
num_uniques as i32
35+
}
36+
}
37+
38+
struct Solution {}

src/leetcode/problem/k_closest.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::cmp::Ordering;
2+
3+
// 973. K Closest Points to Origin, Medium
4+
// https://leetcode.com/problems/k-closest-points-to-origin/
5+
impl Solution {
6+
pub fn k_closest(points: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
7+
let mut enhanced_points = points
8+
.iter()
9+
.map(|n| {
10+
let dist = f64::sqrt(f64::powi(n[0] as f64, 2) + f64::powi(n[1] as f64, 2));
11+
(n[0], n[1], dist)
12+
})
13+
.collect::<Vec<(i32, i32, f64)>>();
14+
enhanced_points.sort_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(Ordering::Equal));
15+
16+
enhanced_points.iter().take(k as usize).map(|n| vec![n.0, n.1]).collect()
17+
}
18+
}
19+
20+
struct Solution {}

src/leetcode/problem/merge.rs

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// 56. Merge Intervals, Medium
2+
// https://leetcode.com/problems/merge-intervals/
3+
impl Solution {
4+
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
5+
let mut intervals = intervals;
6+
intervals.sort_unstable_by(|a, b| a[0].cmp(&b[0]));
7+
let mut ans: Vec<Vec<i32>> = vec![];
8+
9+
for interval in intervals.iter_mut() {
10+
if ans.len() == 0 {
11+
ans.push(interval.clone());
12+
} else {
13+
if interval[0] >= ans.last().unwrap()[0] && interval[1] <= ans.last().unwrap()[1] {
14+
continue;
15+
} else if interval[0] <= ans.last().unwrap()[1] {
16+
ans.last_mut().unwrap()[1] = interval[1];
17+
} else {
18+
ans.push(interval.clone());
19+
}
20+
}
21+
}
22+
23+
ans
24+
}
25+
}
26+
27+
struct Solution {}
28+
29+
mod tests {
30+
use super::*;
31+
use crate::{vec_string, vec_vec_i32};
32+
33+
#[test]
34+
fn test_merge() {
35+
assert_eq!(Solution::merge(vec_vec_i32![[1, 3], [2, 6], [8, 10], [15, 18]]), vec_vec_i32![[1, 6], [8, 10], [15, 18]]);
36+
}
37+
38+
#[test]
39+
fn test_merge2() {
40+
assert_eq!(Solution::merge(vec_vec_i32![[1, 4], [4, 5]]), vec_vec_i32![[1, 5]]);
41+
}
42+
}

src/leetcode/problem/rob.rs

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Definition for a binary tree node.
2+
#[derive(Debug, PartialEq, Eq)]
3+
pub struct TreeNode {
4+
pub val: i32,
5+
pub left: Option<Rc<RefCell<TreeNode>>>,
6+
pub right: Option<Rc<RefCell<TreeNode>>>,
7+
}
8+
9+
impl TreeNode {
10+
#[inline]
11+
pub fn new(val: i32) -> Self {
12+
TreeNode { val, left: None, right: None }
13+
}
14+
}
15+
16+
use std::cell::RefCell;
17+
use std::rc::Rc;
18+
19+
// 337. House Robber III, Medium
20+
// https://leetcode.com/problems/house-robber-iii/
21+
impl Solution {
22+
pub fn rob(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
23+
fn bfs(node: Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) {
24+
if node.is_some() {
25+
let node = node.as_ref().unwrap().borrow();
26+
27+
let l = bfs(node.left.clone());
28+
let r = bfs(node.left.clone());
29+
30+
(node.val + l.1 + r.1, i32::max(l.0, l.1) + i32::max(r.0, r.1))
31+
} else {
32+
(0, 0)
33+
}
34+
}
35+
36+
i32::max(bfs(root.clone()).0, bfs(root.clone()).1)
37+
}
38+
}
39+
40+
struct Solution {}

src/leetcode/problem/stock_span.rs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// 901. Online Stock Span, Medium
2+
// https://leetcode.com/problems/online-stock-span/
3+
impl StockSpanner {
4+
fn new() -> Self {
5+
StockSpanner { prices: vec![] }
6+
}
7+
8+
fn next(&mut self, price: i32) -> i32 {
9+
self.prices.push(price);
10+
11+
let mut i = 0;
12+
for d in (0..self.prices.len()).rev() {
13+
if self.prices[d] <= price {
14+
i += 1;
15+
}
16+
}
17+
18+
i
19+
}
20+
}
21+
22+
struct StockSpanner {
23+
prices: Vec<i32>,
24+
}

src/leetcode/problem/trap.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
use std::collections::VecDeque;
2+
3+
// 42. Trapping Rain Water, Hard
4+
// https://leetcode.com/problems/trapping-rain-water/
5+
impl Solution {
6+
pub fn trap(height: Vec<i32>) -> i32 {
7+
let mut ans = 0;
8+
let mut q = VecDeque::<usize>::new();
9+
10+
for (i, h) in height.iter().enumerate() {
11+
while q.len() > 0 && height[*q.back().unwrap()] < *h {
12+
let top = q.pop_back().unwrap();
13+
if q.len() == 0 {
14+
break;
15+
}
16+
17+
let dist = i - q.back().unwrap() - 1;
18+
let bounded_height = i32::min(*h, height[*q.back().unwrap()]) - height[top];
19+
ans += dist as i32 * bounded_height;
20+
}
21+
22+
q.push_back(i);
23+
}
24+
25+
ans
26+
}
27+
}
28+
29+
struct Solution {}
30+
31+
mod tests {
32+
use super::*;
33+
use crate::{vec_string, vec_vec_i32};
34+
35+
#[test]
36+
fn test_trap() {
37+
assert_eq!(Solution::trap(vec![0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]), 6);
38+
}
39+
40+
#[test]
41+
fn test_trap2() {
42+
assert_eq!(Solution::trap(vec![4, 2, 0, 3, 2, 5]), 9);
43+
}
44+
}

0 commit comments

Comments
 (0)