Skip to content

Commit 9c6e6ef

Browse files
committed
Added tasks 155-295
1 parent fc69f99 commit 9c6e6ef

File tree

21 files changed

+1638
-0
lines changed

21 files changed

+1638
-0
lines changed

README.md

Lines changed: 62 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Rust/LeetCode-in-Rust?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Rust/LeetCode-in-Rust?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust/fork)
3+
4+
## 155\. Min Stack
5+
6+
Easy
7+
8+
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
9+
10+
Implement the `MinStack` class:
11+
12+
* `MinStack()` initializes the stack object.
13+
* `void push(int val)` pushes the element `val` onto the stack.
14+
* `void pop()` removes the element on the top of the stack.
15+
* `int top()` gets the top element of the stack.
16+
* `int getMin()` retrieves the minimum element in the stack.
17+
18+
**Example 1:**
19+
20+
**Input**
21+
22+
["MinStack","push","push","push","getMin","pop","top","getMin"]
23+
[[],[-2],[0],[-3],[],[],[],[]]
24+
25+
**Output:** [null,null,null,null,-3,null,0,-2]
26+
27+
**Explanation:**
28+
29+
MinStack minStack = new MinStack();
30+
minStack.push(-2);
31+
minStack.push(0);
32+
minStack.push(-3);
33+
minStack.getMin(); // return -3
34+
minStack.pop();
35+
minStack.top(); // return 0
36+
minStack.getMin(); // return -2
37+
38+
**Constraints:**
39+
40+
* <code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code>
41+
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
42+
* At most <code>3 * 10<sup>4</sup></code> calls will be made to `push`, `pop`, `top`, and `getMin`.
43+
44+
## Solution
45+
46+
```rust
47+
pub struct MinStack {
48+
current_node: Option<Box<Node>>,
49+
}
50+
51+
/**
52+
* `&self` means the method takes an immutable reference.
53+
* If you need a mutable reference, change it to `&mut self` instead.
54+
*/
55+
struct Node {
56+
min: i32,
57+
data: i32,
58+
next_node: Option<Box<Node>>,
59+
previous_node: Option<Box<Node>>,
60+
}
61+
62+
impl Node {
63+
fn new(min: i32, data: i32, previous_node: Option<Box<Node>>, next_node: Option<Box<Node>>) -> Self {
64+
Node {
65+
min,
66+
data,
67+
next_node,
68+
previous_node,
69+
}
70+
}
71+
}
72+
73+
impl MinStack {
74+
pub fn new() -> Self {
75+
MinStack { current_node: None }
76+
}
77+
78+
pub fn push(&mut self, val: i32) {
79+
match &self.current_node {
80+
None => {
81+
self.current_node = Some(Box::new(Node::new(val, val, None, None)));
82+
}
83+
Some(current) => {
84+
let min = std::cmp::min(current.min, val);
85+
let previous_node = self.current_node.take();
86+
self.current_node = Some(Box::new(Node::new(min, val, previous_node, None)));
87+
}
88+
}
89+
}
90+
91+
pub fn pop(&mut self) {
92+
if let Some(current) = self.current_node.take() {
93+
self.current_node = current.previous_node;
94+
}
95+
}
96+
97+
pub fn top(&self) -> i32 {
98+
if let Some(current) = &self.current_node {
99+
return current.data;
100+
}
101+
panic!("Stack is empty!");
102+
}
103+
104+
pub fn get_min(&self) -> i32 {
105+
if let Some(current) = &self.current_node {
106+
return current.min;
107+
}
108+
panic!("Stack is empty!");
109+
}
110+
}
111+
112+
/**
113+
* Your MinStack object will be instantiated and called as such:
114+
* let obj = MinStack::new();
115+
* obj.push(val);
116+
* obj.pop();
117+
* let ret_3: i32 = obj.top();
118+
* let ret_4: i32 = obj.get_min();
119+
*/
120+
```
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Rust/LeetCode-in-Rust?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Rust/LeetCode-in-Rust?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust/fork)
3+
4+
## 169\. Majority Element
5+
6+
Easy
7+
8+
Given an array `nums` of size `n`, return _the majority element_.
9+
10+
The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [3,2,3]
15+
16+
**Output:** 3
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [2,2,1,1,1,2,2]
21+
22+
**Output:** 2
23+
24+
**Constraints:**
25+
26+
* `n == nums.length`
27+
* <code>1 <= n <= 5 * 10<sup>4</sup></code>
28+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
29+
30+
**Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
31+
32+
## Solution
33+
34+
```rust
35+
impl Solution {
36+
pub fn majority_element(arr: Vec<i32>) -> i32 {
37+
let mut count = 1;
38+
let mut majority = arr[0];
39+
40+
// For Potential Majority Element
41+
for &num in arr.iter().skip(1) {
42+
if num == majority {
43+
count += 1;
44+
} else {
45+
if count > 1 {
46+
count -= 1;
47+
} else {
48+
majority = num;
49+
}
50+
}
51+
}
52+
53+
// For Confirmation
54+
count = 0;
55+
for &num in arr.iter() {
56+
if num == majority {
57+
count += 1;
58+
}
59+
}
60+
61+
if count >= (arr.len() / 2) + 1 {
62+
majority
63+
} else {
64+
-1
65+
}
66+
}
67+
}
68+
```
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Rust/LeetCode-in-Rust?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Rust/LeetCode-in-Rust?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust/fork)
3+
4+
## 189\. Rotate Array
5+
6+
Medium
7+
8+
Given an array, rotate the array to the right by `k` steps, where `k` is non-negative.
9+
10+
**Example 1:**
11+
12+
**Input:** nums = [1,2,3,4,5,6,7], k = 3
13+
14+
**Output:** [5,6,7,1,2,3,4]
15+
16+
**Explanation:**
17+
18+
rotate 1 steps to the right: [7,1,2,3,4,5,6]
19+
20+
rotate 2 steps to the right: [6,7,1,2,3,4,5]
21+
22+
rotate 3 steps to the right: [5,6,7,1,2,3,4]
23+
24+
**Example 2:**
25+
26+
**Input:** nums = [-1,-100,3,99], k = 2
27+
28+
**Output:** [3,99,-1,-100]
29+
30+
**Explanation:**
31+
32+
rotate 1 steps to the right: [99,-1,-100,3]
33+
34+
rotate 2 steps to the right: [3,99,-1,-100]
35+
36+
**Constraints:**
37+
38+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
39+
* <code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code>
40+
* <code>0 <= k <= 10<sup>5</sup></code>
41+
42+
**Follow up:**
43+
44+
* Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem.
45+
* Could you do it in-place with `O(1)` extra space?
46+
47+
## Solution
48+
49+
```rust
50+
impl Solution {
51+
pub fn rotate(nums: &mut Vec<i32>, k: i32) {
52+
let mut rotated = vec![0; nums.len()];
53+
let k_fixed = k as usize % nums.len();
54+
55+
for (i, item) in nums.iter().enumerate() {
56+
match nums.get(i+k_fixed) {
57+
Some(n) => rotated[i+k_fixed] = *item,
58+
None => rotated[(i+k_fixed)-nums.len()] = *item,
59+
}
60+
}
61+
nums.copy_from_slice(&rotated)
62+
}
63+
}
64+
```
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Rust/LeetCode-in-Rust?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Rust/LeetCode-in-Rust?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust/fork)
3+
4+
## 198\. House Robber
5+
6+
Medium
7+
8+
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
9+
10+
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [1,2,3,1]
15+
16+
**Output:** 4
17+
18+
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
19+
20+
**Example 2:**
21+
22+
**Input:** nums = [2,7,9,3,1]
23+
24+
**Output:** 12
25+
26+
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
27+
28+
**Constraints:**
29+
30+
* `1 <= nums.length <= 100`
31+
* `0 <= nums[i] <= 400`
32+
33+
## Solution
34+
35+
```rust
36+
impl Solution {
37+
pub fn rob(nums: Vec<i32>) -> i32 {
38+
if nums.is_empty() {
39+
return 0;
40+
}
41+
if nums.len() == 1 {
42+
return nums[0];
43+
}
44+
if nums.len() == 2 {
45+
return std::cmp::max(nums[0], nums[1]);
46+
}
47+
48+
let mut profit = vec![0; nums.len()];
49+
profit[0] = nums[0];
50+
profit[1] = std::cmp::max(nums[0], nums[1]);
51+
52+
for i in 2..nums.len() {
53+
profit[i] = std::cmp::max(profit[i - 1], nums[i] + profit[i - 2]);
54+
}
55+
56+
profit[nums.len() - 1]
57+
}
58+
}
59+
```

0 commit comments

Comments
 (0)