在最后一个2的时候有4个3都是最大值,要按1/4的概率返回其中一个3的index
public int findMax(vector<int> &arr){. 1point3acres.com/bbs
int len = arr.length();
int ret =-1, max = INT_MIN;. more info on 1point3acres.com
int count=0;
for(int i=0; i<len; i++){. from: 1point3acres.com/bbs
if(arr==max){
count++;
srand(time(NULL));
int judge = rand()%count;
if(judge==0){
ret = i;
}
}
else if(max==INT_MIN || arr>max){
max = arr;
ret = i;. 鐗涗汉浜戦泦,涓€浜╀笁鍒嗗湴
count=1;
}
}
return ret;
}. from: 1point3acres.com/bbs
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution {
private static class Entry {
String taskName;
int timestamp;
boolean start;
public Entry(String name, int timestamp, boolean start) {
this.taskName = name;
this.timestamp = timestamp;
this.start = start;
}
}
private void findExecuteTime(List<Entry> entries) {
Stack<Entry> stk = new Stack<>();
for (Entry entry : entries) {
if (entry.start) {
stk.push(entry);
} else {
int gap = entry.timestamp - stk.pop().timestamp;
System.out.println(entry.taskName + "#" + gap);
for (Entry e : stk) {
e.timestamp += gap;
}
}
}
}
private int randMax(int[] nums) {
int max = nums[0];
int count = 1;
Random r = new Random();
int res = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
count = 1;
res = i;
} else if (nums[i] == max) {
count++;
int s = r.nextInt(count);
if (s == 0) {
res = i;
}
}
}
return res;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.randMax(new int[] {1, 2, 4, 2, 3, 4, 4}));
}
}
==========
public int randomMax(int[] A) {
if (A == null || A.length == 0) {
return -1;
}. 鐗涗汉浜戦泦,涓€浜╀笁鍒嗗湴
int max = A[0];
int index = 1;
for (int i = 1; i < A.length; i++) {
if (A[i] == max) {
int temp = A[index];
A[index] = i;-google 1point3acres
A[i] = temp;
index++;
} else if (A[i] > max) {
max = A[i];
index = 0;
int temp = A[index];
A[index] = i;
A[i] = temp;
index++;
}
}
int random = (int) (Math.random() * index);
return A[random];
}
没有评论:
发表评论