hello算法_C++_ 最差、最佳、平均时间复杂度
算法的时间效率往往不是固定的,而是与输入数据的分布有关。假设输入一个长度为 的数组 nums
,其中 nums
由从 1 至 n 的数字组成,每个数字只出现一次;但元素顺序是随机打乱的,任务目标是返回元素 的索引。我们可以得出以下结论。
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
#include <random>using namespace std;// 生成数组 {1, 2, ..., n} 并随机打乱
vector<int> randomNumbers(int n) {vector<int> nums(n);for (int i = 0; i < n; i++) {nums[i] = i + 1;}unsigned seed = chrono::system_clock::now().time_since_epoch().count();shuffle(nums.begin(), nums.end(), default_random_engine(seed));return nums;
}// 查找数字 1 在数组中的索引
int findOne(vector<int> &nums) {for (int i = 0; i < nums.size(); i++) {if (nums[i] == 1)return i;// cout << i << endl; // 可以根据需要输出,调试用}return -1;
}int main() {int n = 10; // 你可以修改 n 的值vector<int> arr = randomNumbers(n);// 输出数组内容cout << "打乱的数组:";for (int num : arr) {cout << num << " ";}cout << endl;int index = findOne(arr);if (index != -1) {cout << "元素 1 在数组中的索引是:" << index << endl;} else {cout << "数组中没有元素 1" << endl;}return 0;
}