#include <vector>
#include <iostream>
#include <cstdlib>
#include <climits>
#include <time.h>
using namespace std;
// naive method
// Go through the array once, find the max and the number of occurrences (n)
// Generate a random number (r) between 1 and n
// Go through the array again, return rth occurrance.
int randomIndex(vector<int>& nums) {
int max_val = INT_MIN;
int count = 0;
for(int i = 0; i < nums.size(); ++i) {
if(nums[i] > max_val) {
max_val = nums[i];
count = 1;
} else if(nums[i] == max_val) {
count++;
}
}
srand(time(NULL));
int random_value = rand() % count + 1;
cout << random_value << endl;
cout << "random value is" << endl;
int max_index = 1;
for(int i = 0; i < nums.size(); ++i) {
if(nums[i] == max_val && max_index == random_value) {
return i;
} else if(nums[i] == max_val) max_index++;
}
}
int main(void) {
vector<int> nums{2, 1, 2, 1, 5, 4, 5, 5};
cout << randomIndex(nums) << endl;
}
Maximum value's random index
最新推荐文章于 2020-12-20 13:47:18 发布