就是一个int array 里面会有一到多个maximum,返回一个随机maximum的index
// 2 pass, o(n) time, o(n) space
public int index(int[] nums) {
int max = Integer.MIN_VALUE;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
max = Math.max(max, nums[i]);
}
for (int i = 0; i < nums.length; i++) {
if (max == nums[i]) {
list.add(i);
}
}
return list.get(new Random().nextInt(list.size()));
}
// wrong
// two pass, n time, 1 space
public int index0(int[] nums) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
max = Math.max(max, nums[i]);
}
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (max == nums[i]) {
nums[j] = i;
j++;
}
}
return nums[new Random().nextInt(j)];
}
// one pass
public int find(int[] A) {
Random rand = new Random();
int[] reservior = new int[1];
int maxValue = Integer.MIN_VALUE;
int numOfMaxValue = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] == maxValue) {
numOfMaxValue++;
int randNum = rand.nextInt(numOfMaxValue);
if (randNum < 1) {
reservior[0] = i;
}
}
if (A[i] > maxValue) {
maxValue = A[i];
numOfMaxValue = 1;
reservior[0] = i;
}
}
return reservior[0];
}
public static void main(String[] args) {
FindIndexOfMaxValue example = new FindIndexOfMaxValue();
int count4 = 0, count6 = 0;
int[] A = { 1, 2, 3, 4, 5, 3, 5 };
for (int i = 0; i < 10000; i++) {
int res = example.find(A);
if (res == 4) {
count4++;
}
if (res == 6) {
count6++;
}
}
System.out.println("6 appears " + count6 + " times");
System.out.println("4 appears " + count4 + " times");
count4 = 0;
count6 = 0;
int[] B = { 1, 2, 3, 4, 5, 3, 5 };
for (int i = 0; i < 10000; i++) {
int res = example.index(B);
if (res == 4) {
count4++;
}
if (res == 6) {
count6++;
}
}
System.out.println("6 appears " + count6 + " times");
System.out.println("4 appears " + count4 + " times");
count4 = 0;
count6 = 0;
int[] C = { 1, 2, 3, 4, 5, 3, 5 };
for (int i = 0; i < 10000; i++) {
int res = example.index0(C);
if (res == 4) {
count4++;
}
if (res == 6) {
count6++;
}
}
System.out.println("6 appears " + count6 + " times");
System.out.println("4 appears " + count4 + " times");
}