mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-17 14:10:57 +00:00
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:
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user