算法的時間效率往往不是固定的,而是與輸入數據的分布有關。假設輸入一個長度為??的數組?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;
}