copy zig codes of chapter_array_and_linkedlist and chapter_computatio… (#319)

* copy zig codes of chapter_array_and_linkedlist and chapter_computational_complexity to markdown files

* Update time_complexity.md

---------

Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
sjinzh
2023-02-03 19:15:34 +08:00
committed by GitHub
parent b39b84acba
commit 15efaca85d
8 changed files with 566 additions and 41 deletions

View File

@ -178,7 +178,23 @@ comments: true
=== "Zig"
```zig title="leetcode_two_sum.zig"
const SolutionBruteForce = struct {
pub fn twoSum(self: *SolutionBruteForce, nums: []i32, target: i32) [2]i32 {
_ = self;
var size: usize = nums.len;
var i: usize = 0;
// 两层循环,时间复杂度 O(n^2)
while (i < size - 1) : (i += 1) {
var j = i + 1;
while (j < size) : (j += 1) {
if (nums[i] + nums[j] == target) {
return [_]i32{@intCast(i32, i), @intCast(i32, j)};
}
}
}
return undefined;
}
};
```
### 方法二:辅助哈希表
@ -347,5 +363,22 @@ comments: true
=== "Zig"
```zig title="leetcode_two_sum.zig"
const SolutionHashMap = struct {
pub fn twoSum(self: *SolutionHashMap, nums: []i32, target: i32) ![2]i32 {
_ = self;
var size: usize = nums.len;
// 辅助哈希表,空间复杂度 O(n)
var dic = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
defer dic.deinit();
var i: usize = 0;
// 单层循环,时间复杂度 O(n)
while (i < size) : (i += 1) {
if (dic.contains(target - nums[i])) {
return [_]i32{dic.get(target - nums[i]).?, @intCast(i32, i)};
}
try dic.put(nums[i], @intCast(i32, i));
}
return undefined;
}
};
```