Maximum value's random index
来源:互联网 发布:c语言while语句举例 编辑:程序博客网 时间:2024/06/06 02:01
#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;}
0 0
- Maximum value's random index
- Maximum Index
- Maximum Value
- Maximum Value
- 398. Random Pick Index
- 398. Random Pick Index
- Random Pick Index
- Random Pick Index
- Random Pick Index
- 398. Random Pick Index
- Random Pick Index
- 398. Random Pick Index
- 398. Random Pick Index
- 398. Random Pick Index**
- leetcode_middle_38_398. Random Pick Index
- leetcode398: Random Pick Index
- 398. Random Pick Index
- Random Pick Index
- 群英荟萃
- Node.js
- Linux学习之字符处理命令
- 10.5.1节练习
- Collection
- Maximum value's random index
- 继承
- Android UI开发: 横向ListView(HorizontalListView)及一个简单相册的完整实现 (附源码下载)
- SQL SERVER2008数据库导入MySQL数据库
- 开启写日志的生活之旅
- UML建模相关概念
- Unsupervised Nearest Neighbors Clustering With Application to Hyperspectral Images
- 2016年团体程序设计天梯赛-初赛 - 到底有多二 - Java
- 机房收费系统总结篇(三)