Skip to content

Commit fa64f16

Browse files
authoredMay 30, 2024··
feat: add solutions to lc problems: No.362,364 (#2968)
* No.0362.Design Hit Counter * No.0364.Nested List Weight Sum II
1 parent ff06d9e commit fa64f16

File tree

22 files changed

+1086
-338
lines changed

22 files changed

+1086
-338
lines changed
 

‎basic/sorting/HeapSort/README.md

-8
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,6 @@ for (int i = n / 2; i > 0; --i) {
7171

7272
<!-- tabs:start -->
7373

74-
### **Python3**
75-
7674
#### Python3
7775

7876
```python
@@ -112,8 +110,6 @@ for i in range(m):
112110
print(' '.join(list(map(str, res))))
113111
```
114112

115-
### **Java**
116-
117113
#### Java
118114

119115
```java
@@ -169,8 +165,6 @@ public class Main {
169165
}
170166
```
171167

172-
### **Rust**
173-
174168
#### Rust
175169

176170
```rust
@@ -236,8 +230,6 @@ fn main() -> io::Result<()> {
236230
}
237231
```
238232

239-
### **Go**
240-
241233
#### Go
242234

243235
```go

‎lcof/面试题63. 股票的最大利润/README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -181,12 +181,12 @@ class Solution {
181181
func maxProfit(_ prices: [Int]) -> Int {
182182
var mi = Int.max
183183
var ans = 0
184-
184+
185185
for x in prices {
186186
ans = max(ans, x - mi)
187187
mi = min(mi, x)
188188
}
189-
189+
190190
return ans
191191
}
192192
}

‎lcof/面试题66. 构建乘积数组/README.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -195,21 +195,21 @@ class Solution {
195195
func constructArr(_ a: [Int]) -> [Int] {
196196
let n = a.count
197197
guard n > 0 else { return [] }
198-
198+
199199
var ans = [Int](repeating: 1, count: n)
200-
200+
201201
var left = 1
202202
for i in 0..<n {
203203
ans[i] = left
204204
left *= a[i]
205205
}
206-
206+
207207
var right = 1
208208
for i in (0..<n).reversed() {
209209
ans[i] *= right
210210
right *= a[i]
211211
}
212-
212+
213213
return ans
214214
}
215215
}

‎lcof2/剑指 Offer II 002. 二进制加法/README.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -189,22 +189,22 @@ class Solution {
189189
var result = ""
190190
var carry = 0
191191
var i = a.count - 1, j = b.count - 1
192-
192+
193193
let aChars = Array(a)
194194
let bChars = Array(b)
195-
195+
196196
while i >= 0 || j >= 0 || carry > 0 {
197197
let digitA = i >= 0 ? Int(String(aChars[i]))! : 0
198198
let digitB = j >= 0 ? Int(String(bChars[j]))! : 0
199-
199+
200200
carry += digitA + digitB
201201
result = "\(carry % 2)" + result
202202
carry /= 2
203-
203+
204204
i -= 1
205205
j -= 1
206206
}
207-
207+
208208
return result
209209
}
210210
}

‎solution/0300-0399/0362.Design Hit Counter/README.md

+143-49
Original file line numberDiff line numberDiff line change
@@ -74,33 +74,27 @@ counter.getHits(301); // 在时刻 301 统计过去 5 分钟内的敲击次数
7474

7575
<!-- solution:start -->
7676

77-
### 方法一
77+
### 方法一:二分查找
78+
79+
由于 `timestamp` 是单调递增的,我们可以使用一个数组 `ts` 来存储所有的 `timestamp`,然后在 `getHits` 方法中使用二分查找找到第一个大于等于 `timestamp - 300 + 1` 的位置,然后返回 `ts` 的长度减去这个位置即可。
80+
81+
时间复杂度方面,`hit` 方法的时间复杂度为 $O(1)$,`getHits` 方法的时间复杂度为 $O(\log n)$。其中 $n$ 为 `ts` 的长度。
7882

7983
<!-- tabs:start -->
8084

8185
#### Python3
8286

8387
```python
8488
class HitCounter:
89+
8590
def __init__(self):
86-
"""
87-
Initialize your data structure here.
88-
"""
89-
self.counter = Counter()
91+
self.ts = []
9092

9193
def hit(self, timestamp: int) -> None:
92-
"""
93-
Record a hit.
94-
@param timestamp - The current timestamp (in seconds granularity).
95-
"""
96-
self.counter[timestamp] += 1
94+
self.ts.append(timestamp)
9795

9896
def getHits(self, timestamp: int) -> int:
99-
"""
100-
Return the number of hits in the past 5 minutes.
101-
@param timestamp - The current timestamp (in seconds granularity).
102-
"""
103-
return sum([v for t, v in self.counter.items() if t + 300 > timestamp])
97+
return len(self.ts) - bisect_left(self.ts, timestamp - 300 + 1)
10498

10599

106100
# Your HitCounter object will be instantiated and called as such:
@@ -113,34 +107,31 @@ class HitCounter:
113107

114108
```java
115109
class HitCounter {
110+
private List<Integer> ts = new ArrayList<>();
116111

117-
private Map<Integer, Integer> counter;
118-
119-
/** Initialize your data structure here. */
120112
public HitCounter() {
121-
counter = new HashMap<>();
122113
}
123114

124-
/**
125-
Record a hit.
126-
@param timestamp - The current timestamp (in seconds granularity).
127-
*/
128115
public void hit(int timestamp) {
129-
counter.put(timestamp, counter.getOrDefault(timestamp, 0) + 1);
116+
ts.add(timestamp);
130117
}
131118

132-
/**
133-
Return the number of hits in the past 5 minutes.
134-
@param timestamp - The current timestamp (in seconds granularity).
135-
*/
136119
public int getHits(int timestamp) {
137-
int hits = 0;
138-
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
139-
if (entry.getKey() + 300 > timestamp) {
140-
hits += entry.getValue();
120+
int l = search(timestamp - 300 + 1);
121+
return ts.size() - l;
122+
}
123+
124+
private int search(int x) {
125+
int l = 0, r = ts.size();
126+
while (l < r) {
127+
int mid = (l + r) >> 1;
128+
if (ts.get(mid) >= x) {
129+
r = mid;
130+
} else {
131+
l = mid + 1;
141132
}
142133
}
143-
return hits;
134+
return l;
144135
}
145136
}
146137

@@ -152,39 +143,142 @@ class HitCounter {
152143
*/
153144
```
154145

146+
#### C++
147+
148+
```cpp
149+
class HitCounter {
150+
public:
151+
HitCounter() {
152+
153+
}
154+
155+
void hit(int timestamp) {
156+
ts.push_back(timestamp);
157+
}
158+
159+
int getHits(int timestamp) {
160+
return ts.end() - lower_bound(ts.begin(), ts.end(), timestamp - 300 + 1);
161+
}
162+
163+
private:
164+
vector<int> ts;
165+
};
166+
167+
/**
168+
* Your HitCounter object will be instantiated and called as such:
169+
* HitCounter* obj = new HitCounter();
170+
* obj->hit(timestamp);
171+
* int param_2 = obj->getHits(timestamp);
172+
*/
173+
```
174+
175+
#### Go
176+
177+
```go
178+
type HitCounter struct {
179+
ts []int
180+
}
181+
182+
func Constructor() HitCounter {
183+
return HitCounter{}
184+
}
185+
186+
func (this *HitCounter) Hit(timestamp int) {
187+
this.ts = append(this.ts, timestamp)
188+
}
189+
190+
func (this *HitCounter) GetHits(timestamp int) int {
191+
return len(this.ts) - sort.SearchInts(this.ts, timestamp-300+1)
192+
}
193+
194+
/**
195+
* Your HitCounter object will be instantiated and called as such:
196+
* obj := Constructor();
197+
* obj.Hit(timestamp);
198+
* param_2 := obj.GetHits(timestamp);
199+
*/
200+
```
201+
202+
#### TypeScript
203+
204+
```ts
205+
class HitCounter {
206+
private ts: number[] = [];
207+
208+
constructor() {}
209+
210+
hit(timestamp: number): void {
211+
this.ts.push(timestamp);
212+
}
213+
214+
getHits(timestamp: number): number {
215+
const search = (x: number) => {
216+
let [l, r] = [0, this.ts.length];
217+
while (l < r) {
218+
const mid = (l + r) >> 1;
219+
if (this.ts[mid] >= x) {
220+
r = mid;
221+
} else {
222+
l = mid + 1;
223+
}
224+
}
225+
return l;
226+
};
227+
return this.ts.length - search(timestamp - 300 + 1);
228+
}
229+
}
230+
231+
/**
232+
* Your HitCounter object will be instantiated and called as such:
233+
* var obj = new HitCounter()
234+
* obj.hit(timestamp)
235+
* var param_2 = obj.getHits(timestamp)
236+
*/
237+
```
238+
155239
#### Rust
156240

157241
```rust
158-
use std::{ collections::BinaryHeap, cmp::Reverse };
159-
160242
struct HitCounter {
161-
/// A min heap
162-
pq: BinaryHeap<Reverse<i32>>,
243+
ts: Vec<i32>,
163244
}
164245

246+
/**
247+
* `&self` means the method takes an immutable reference.
248+
* If you need a mutable reference, change it to `&mut self` instead.
249+
*/
165250
impl HitCounter {
166251
fn new() -> Self {
167-
Self {
168-
pq: BinaryHeap::new(),
169-
}
252+
HitCounter { ts: Vec::new() }
170253
}
171254

172255
fn hit(&mut self, timestamp: i32) {
173-
self.pq.push(Reverse(timestamp));
256+
self.ts.push(timestamp);
174257
}
175258

176-
fn get_hits(&mut self, timestamp: i32) -> i32 {
177-
while let Some(Reverse(min_elem)) = self.pq.peek() {
178-
if *min_elem <= timestamp - 300 {
179-
self.pq.pop();
259+
fn get_hits(&self, timestamp: i32) -> i32 {
260+
let l = self.search(timestamp - 300 + 1);
261+
(self.ts.len() - l) as i32
262+
}
263+
264+
fn search(&self, x: i32) -> usize {
265+
let (mut l, mut r) = (0, self.ts.len());
266+
while l < r {
267+
let mid = (l + r) / 2;
268+
if self.ts[mid] >= x {
269+
r = mid;
180270
} else {
181-
break;
271+
l = mid + 1;
182272
}
183273
}
184-
185-
self.pq.len() as i32
274+
l
186275
}
187-
}
276+
}/**
277+
* Your HitCounter object will be instantiated and called as such:
278+
* let obj = HitCounter::new();
279+
* obj.hit(timestamp);
280+
* let ret_2: i32 = obj.get_hits(timestamp);
281+
*/
188282
```
189283

190284
<!-- tabs:end -->

0 commit comments

Comments
 (0)
Please sign in to comment.