This commit is contained in:
krahets
2023-10-17 00:34:03 +08:00
parent e181f9b491
commit 44ebc7748b
4 changed files with 17 additions and 10 deletions

View File

@ -3284,11 +3284,11 @@ $$
```zig title="worst_best_time_complexity.zig"
// 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱
pub fn randomNumbers(comptime n: usize) [n]i32 {
fn randomNumbers(comptime n: usize) [n]i32 {
var nums: [n]i32 = undefined;
// 生成数组 nums = { 1, 2, 3, ..., n }
for (nums) |*num, i| {
num.* = @intCast(i32, i) + 1;
for (&nums, 0..) |*num, i| {
num.* = @as(i32, @intCast(i)) + 1;
}
// 随机打乱数组元素
const rand = std.crypto.random;
@ -3297,11 +3297,11 @@ $$
}
// 查找数组 nums 中数字 1 所在索引
pub fn findOne(nums: []i32) i32 {
for (nums) |num, i| {
fn findOne(nums: []i32) i32 {
for (nums, 0..) |num, i| {
// 当元素 1 在数组头部时,达到最佳时间复杂度 O(1)
// 当元素 1 在数组尾部时,达到最差时间复杂度 O(n)
if (num == 1) return @intCast(i32, i);
if (num == 1) return @intCast(i);
}
return -1;
}