"Coding Interview Guide" -- 从N个数中等概率打印M个数

题目

  给定一个长度为N且没有重复元素的数组arr和一个整数m,实现函数等概率随机打印arr中的M个数

要求

  1、相同的数不要重复打印;

  2、时间复杂度为O(M),额外空间复杂度为O(1);

  3、可以改变数组arr

  import java.util.Random;  

1
public void printRandM1(int[] arr, int m) 2 { 3 if(arr == null || arr.length < m) 4 { 5   return; 6 } 7 8 Random rd = new Random(); 9 int index = 0; 10 int maxIndex = arr.length; 11 while(m-- != 0) 12 { 13   index = rd.nextInt(maxIndex--); // public int nextInt(int n)方法随机返回一个位于区间[0, n)的整型值 14   System.out.println(arr[index]); 15   swap(arr, index, maxIndex); 16 } 17 } 18 19 public void swap(int[] arr, int i, int j) 20 { 21 int temp = arr[i]; 22 arr[i] = arr[j]; 23 arr[j] = temp; 24 }

来源:左程云老师《程序员代码面试指南》

猜你喜欢

转载自www.cnblogs.com/latup/p/10973152.html