zig : upgrade codes && rust : add codes for chapter_searching and chapter_dynamic_programming. (#591)

* zig : update zig codes

* rust : add codes for linear_search and hashing_search

* rust : add codes for linear_search and hashing_search

* rust : add codes for chapter_dynamic_programming
This commit is contained in:
sjinzh
2023-07-10 01:32:12 +08:00
committed by GitHub
parent 6c133d42d5
commit 459449d41a
21 changed files with 485 additions and 187 deletions
@@ -18,7 +18,7 @@ fn binarySearch(comptime T: type, nums: std.ArrayList(T), target: T) T {
} else if (nums.items[m] > target) { // 此情况说明 target 在区间 [i, m-1] 中
j = m - 1;
} else { // 找到目标元素,返回其索引
return @intCast(T, m);
return @intCast(m);
}
}
// 未找到目标元素,返回 -1
@@ -38,7 +38,7 @@ fn binarySearchLCRO(comptime T: type, nums: std.ArrayList(T), target: T) T {
} else if (nums.items[m] > target) { // 此情况说明 target 在区间 [i, m) 中
j = m;
} else { // 找到目标元素,返回其索引
return @intCast(T, m);
return @intCast(m);
}
}
// 未找到目标元素,返回 -1
@@ -31,7 +31,7 @@ pub fn main() !void {
var map = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
defer map.deinit();
for (nums, 0..) |num, i| {
try map.put(num, @intCast(i32, i)); // key: 元素,value: 索引
try map.put(num, @as(i32, @intCast(i))); // key: 元素,value: 索引
}
var index = hashingSearchArray(i32, map, target);
std.debug.print("目标元素 3 的索引 = {}\n", .{index});
@@ -11,7 +11,7 @@ fn linearSearchArray(comptime T: type, nums: std.ArrayList(T), target: T) T {
for (nums.items, 0..) |num, i| {
// 找到目标元素, 返回其索引
if (num == target) {
return @intCast(T, i);
return @intCast(i);
}
}
// 未找到目标元素,返回 -1
+3 -3
View File
@@ -14,7 +14,7 @@ pub fn twoSumBruteForce(nums: []i32, target: i32) ?[2]i32 {
var j = i + 1;
while (j < size) : (j += 1) {
if (nums[i] + nums[j] == target) {
return [_]i32{@intCast(i32, i), @intCast(i32, j)};
return [_]i32{@intCast(i), @intCast(j)};
}
}
}
@@ -31,9 +31,9 @@ pub fn twoSumHashTable(nums: []i32, target: i32) !?[2]i32 {
// 单层循环,时间复杂度 O(n)
while (i < size) : (i += 1) {
if (dic.contains(target - nums[i])) {
return [_]i32{dic.get(target - nums[i]).?, @intCast(i32, i)};
return [_]i32{dic.get(target - nums[i]).?, @intCast(i)};
}
try dic.put(nums[i], @intCast(i32, i));
try dic.put(nums[i], @intCast(i));
}
return null;
}