随机数索引

给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。

注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。

public class RandomIndex {
	int[] nums;

	public RandomIndex(int[] nums) {
		this.nums = nums;
	}

	public int pick(int target) {
		int index = -1;
		int count = 1;
		Random ran = new Random();
		for (int i = 0; i < nums.length; i++) {
			if(nums[i] == target){
				if (ran.nextInt(count++) == 0) {
					index = i;
				}
			}
		}
		return index;
	}
}

猜你喜欢

转载自blog.csdn.net/gkq_tt/article/details/88533656