cpp-algo-cases/chapter_computational_compl.../worst_best_time_complexity.cpp

46 lines
1.2 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: worst_best_time_complexity.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>飬Ԫ<E9A3AC><D4AA>Ϊ { 1, 2, ..., n }<7D><>˳<EFBFBD>򱻴<EFBFBD><F2B1BBB4><EFBFBD> */
vector<int> randomNumbers(int n) {
vector<int> nums(n);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// ʹ<><CAB9>ϵͳʱ<CDB3><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>
shuffle(nums.begin(), nums.end(), default_random_engine(seed));
return nums;
}
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> nums <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
int findOne(vector<int> &nums) {
for (int i = 0; i < nums.size(); i++) {
// <20><>Ԫ<EFBFBD><D4AA> 1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͷ<EFBFBD><CDB7>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFB5BD><EFBFBD><EFBFBD>ʱ<EFBFBD><EFBFBD>Ӷ<EFBFBD> O(1)
// <20><>Ԫ<EFBFBD><D4AA> 1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>β<EFBFBD><CEB2>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFB5BD><EFBFBD><EFBFBD>ʱ<EFBFBD><EFBFBD>Ӷ<EFBFBD> O(n)
if (nums[i] == 1)
return i;
}
return -1;
}
/* Driver Code */
int main() {
for (int i = 0; i < 1000; i++) {
int n = 100;
vector<int> nums = randomNumbers(n);
int index = findOne(nums);
cout << "\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD> [ 1, 2, ..., n ] <20><><EFBFBD><EFBFBD><EFBFBD>Һ<EFBFBD> = ";
printVector(nums);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << index << endl;
}
return 0;
}