Skip to content

feat: add solutions to lc problems: No.362,364 #2968

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions basic/sorting/HeapSort/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ for (int i = n / 2; i > 0; --i) {

<!-- tabs:start -->

### **Python3**

#### Python3

```python
Expand Down Expand Up @@ -112,8 +110,6 @@ for i in range(m):
print(' '.join(list(map(str, res))))
```

### **Java**

#### Java

```java
Expand Down Expand Up @@ -169,8 +165,6 @@ public class Main {
}
```

### **Rust**

#### Rust

```rust
Expand Down Expand Up @@ -236,8 +230,6 @@ fn main() -> io::Result<()> {
}
```

### **Go**

#### Go

```go
Expand Down
4 changes: 2 additions & 2 deletions lcof/面试题63. 股票的最大利润/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,12 @@ class Solution {
func maxProfit(_ prices: [Int]) -> Int {
var mi = Int.max
var ans = 0

for x in prices {
ans = max(ans, x - mi)
mi = min(mi, x)
}

return ans
}
}
Expand Down
8 changes: 4 additions & 4 deletions lcof/面试题66. 构建乘积数组/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,21 +195,21 @@ class Solution {
func constructArr(_ a: [Int]) -> [Int] {
let n = a.count
guard n > 0 else { return [] }

var ans = [Int](repeating: 1, count: n)

var left = 1
for i in 0..<n {
ans[i] = left
left *= a[i]
}

var right = 1
for i in (0..<n).reversed() {
ans[i] *= right
right *= a[i]
}

return ans
}
}
Expand Down
10 changes: 5 additions & 5 deletions lcof2/剑指 Offer II 002. 二进制加法/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,22 +189,22 @@ class Solution {
var result = ""
var carry = 0
var i = a.count - 1, j = b.count - 1

let aChars = Array(a)
let bChars = Array(b)

while i >= 0 || j >= 0 || carry > 0 {
let digitA = i >= 0 ? Int(String(aChars[i]))! : 0
let digitB = j >= 0 ? Int(String(bChars[j]))! : 0

carry += digitA + digitB
result = "\(carry % 2)" + result
carry /= 2

i -= 1
j -= 1
}

return result
}
}
Expand Down
192 changes: 143 additions & 49 deletions solution/0300-0399/0362.Design Hit Counter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,33 +74,27 @@ counter.getHits(301); // 在时刻 301 统计过去 5 分钟内的敲击次数

<!-- solution:start -->

### 方法一
### 方法一:二分查找

由于 `timestamp` 是单调递增的,我们可以使用一个数组 `ts` 来存储所有的 `timestamp`,然后在 `getHits` 方法中使用二分查找找到第一个大于等于 `timestamp - 300 + 1` 的位置,然后返回 `ts` 的长度减去这个位置即可。

时间复杂度方面,`hit` 方法的时间复杂度为 $O(1)$,`getHits` 方法的时间复杂度为 $O(\log n)$。其中 $n$ 为 `ts` 的长度。

<!-- tabs:start -->

#### Python3

```python
class HitCounter:

def __init__(self):
"""
Initialize your data structure here.
"""
self.counter = Counter()
self.ts = []

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

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


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

```java
class HitCounter {
private List<Integer> ts = new ArrayList<>();

private Map<Integer, Integer> counter;

/** Initialize your data structure here. */
public HitCounter() {
counter = new HashMap<>();
}

/**
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
*/
public void hit(int timestamp) {
counter.put(timestamp, counter.getOrDefault(timestamp, 0) + 1);
ts.add(timestamp);
}

/**
Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity).
*/
public int getHits(int timestamp) {
int hits = 0;
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
if (entry.getKey() + 300 > timestamp) {
hits += entry.getValue();
int l = search(timestamp - 300 + 1);
return ts.size() - l;
}

private int search(int x) {
int l = 0, r = ts.size();
while (l < r) {
int mid = (l + r) >> 1;
if (ts.get(mid) >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return hits;
return l;
}
}

Expand All @@ -152,39 +143,142 @@ class HitCounter {
*/
```

#### C++

```cpp
class HitCounter {
public:
HitCounter() {

}

void hit(int timestamp) {
ts.push_back(timestamp);
}

int getHits(int timestamp) {
return ts.end() - lower_bound(ts.begin(), ts.end(), timestamp - 300 + 1);
}

private:
vector<int> ts;
};

/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter* obj = new HitCounter();
* obj->hit(timestamp);
* int param_2 = obj->getHits(timestamp);
*/
```

#### Go

```go
type HitCounter struct {
ts []int
}

func Constructor() HitCounter {
return HitCounter{}
}

func (this *HitCounter) Hit(timestamp int) {
this.ts = append(this.ts, timestamp)
}

func (this *HitCounter) GetHits(timestamp int) int {
return len(this.ts) - sort.SearchInts(this.ts, timestamp-300+1)
}

/**
* Your HitCounter object will be instantiated and called as such:
* obj := Constructor();
* obj.Hit(timestamp);
* param_2 := obj.GetHits(timestamp);
*/
```

#### TypeScript

```ts
class HitCounter {
private ts: number[] = [];

constructor() {}

hit(timestamp: number): void {
this.ts.push(timestamp);
}

getHits(timestamp: number): number {
const search = (x: number) => {
let [l, r] = [0, this.ts.length];
while (l < r) {
const mid = (l + r) >> 1;
if (this.ts[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
return this.ts.length - search(timestamp - 300 + 1);
}
}

/**
* Your HitCounter object will be instantiated and called as such:
* var obj = new HitCounter()
* obj.hit(timestamp)
* var param_2 = obj.getHits(timestamp)
*/
```

#### Rust

```rust
use std::{ collections::BinaryHeap, cmp::Reverse };

struct HitCounter {
/// A min heap
pq: BinaryHeap<Reverse<i32>>,
ts: Vec<i32>,
}

/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl HitCounter {
fn new() -> Self {
Self {
pq: BinaryHeap::new(),
}
HitCounter { ts: Vec::new() }
}

fn hit(&mut self, timestamp: i32) {
self.pq.push(Reverse(timestamp));
self.ts.push(timestamp);
}

fn get_hits(&mut self, timestamp: i32) -> i32 {
while let Some(Reverse(min_elem)) = self.pq.peek() {
if *min_elem <= timestamp - 300 {
self.pq.pop();
fn get_hits(&self, timestamp: i32) -> i32 {
let l = self.search(timestamp - 300 + 1);
(self.ts.len() - l) as i32
}

fn search(&self, x: i32) -> usize {
let (mut l, mut r) = (0, self.ts.len());
while l < r {
let mid = (l + r) / 2;
if self.ts[mid] >= x {
r = mid;
} else {
break;
l = mid + 1;
}
}

self.pq.len() as i32
l
}
}
}/**
* Your HitCounter object will be instantiated and called as such:
* let obj = HitCounter::new();
* obj.hit(timestamp);
* let ret_2: i32 = obj.get_hits(timestamp);
*/
```

<!-- tabs:end -->
Expand Down
Loading
Loading