find random maximum

本文介绍了一种从整数数组中随机选择最大值索引的方法,并提供了三种不同的实现方式:使用列表存储最大值索引、修改原数组来存储最大值索引以及使用蓄水池抽样算法进行单次遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

就是一个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");
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值