Skip to content

Commit

Permalink
leetcode: Update 0001
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Sep 25, 2024
1 parent a3ce1f8 commit cbd4593
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/leetcode/0001.two-sum/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@

![hash-table](assets/hash-table.svg)

这个方法的时间复杂度是 `O(nlogn)`.
这个方法的时间复杂度是 `O(n)`.

```rust
{{#include src/main.rs:18:34 }}
```
```
11 changes: 9 additions & 2 deletions src/leetcode/0001.two-sum/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
#include <cassert>
#include <cstdio>

#include <map>
#include <unordered_map>
#include <vector>

class Solution {
Expand All @@ -29,21 +29,28 @@ class Solution {

static
std::vector<int> twoSum2(std::vector<int>& nums, int target) {
// 检查边界条件
if (nums.size() < 2) {
return {};
}

std::map<int, int> cache;
// 使用哈稀表来缓存遍历过的整数 num
// (num, index)
std::unordered_map<int, int> cache;
// 遍历数组
for (int i = 0; i < nums.size(); ++i) {
const int num = nums[i];
const auto iter = cache.find(target - num);
// 找到了合适的两数, 它们的和等于 target
if (iter != cache.cend()) {
return {iter->second, i};
} else {
// 缓存当前的整数
cache.emplace(num, i);
}
}

// 遍历所有整数后还是没有找到
return {};
}
};
Expand Down
5 changes: 5 additions & 0 deletions src/leetcode/0014.longest-common-prefix/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,27 @@
char* longestCommonPrefix(char** strs, int strsSize) {
int index = 0;
int stop = 0;

while (!stop) {
// 第一个字符串结束了
if (strs[0][index] == '\0') {
break;
}

// 遍历每个字符串, 检查它们在当前位置的字是否相等
for (int i = 1; i < strsSize; ++i) {
if (strs[0][index] != strs[i][index]) {
stop = 1;
break;
}
}
// 如果当前位置的字符都相同, 就继续检查下一个字符
if (!stop) {
index += 1;
}
}

// 构造字符串, 注意结尾是 '\0'
char* out = (char*)malloc(index + 1);
assert(out);
memcpy(out, strs[0], index);
Expand Down

0 comments on commit cbd4593

Please sign in to comment.