From 1ec97120a92543d8183e11908d9d24e69a3546c4 Mon Sep 17 00:00:00 2001 From: machangxin Date: Tue, 13 Dec 2022 17:53:23 +0800 Subject: [PATCH] add worst_best_time_complexity.go --- .../worst_best_time_complexity.go | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 codes/go/chapter_computational_complexity/time_complexity/worst_best_time_complexity.go diff --git a/codes/go/chapter_computational_complexity/time_complexity/worst_best_time_complexity.go b/codes/go/chapter_computational_complexity/time_complexity/worst_best_time_complexity.go new file mode 100644 index 000000000..bc3e79010 --- /dev/null +++ b/codes/go/chapter_computational_complexity/time_complexity/worst_best_time_complexity.go @@ -0,0 +1,45 @@ +// File: worst_best_time_complexity.go +// Created Time: 2022-12-13 +// Author: msk397 (machangxinq@gmail.com) + +package time_complexity + +import ( + "fmt" + "math/rand" +) + +/* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */ +func randomNumbers(n int) []int { + nums := make([]int, n) + // 生成数组 nums = { 1, 2, 3, ..., n } + for i := 0; i < n; i++ { + nums[i] = i + 1 + } + // 随机打乱数组元素 + rand.Shuffle(len(nums), func(i, j int) { + nums[i], nums[j] = nums[j], nums[i] + }) + return nums +} + +/* 查找数组 nums 中数字 1 所在索引 */ +func findOne(nums []int) int { + for i := 0; i < len(nums); i++ { + if nums[i] == 1 { + return i + } + } + return -1 +} + +/* Driver Code */ +func main() { + for i := 0; i < 10; i++ { + n := 100 + nums := randomNumbers(n) + index := findOne(nums) + fmt.Println("\n数组 [ 1, 2, ..., n ] 被打乱后 =", nums) + fmt.Println("数字 1 的索引为", index) + } +}