zoukankan      html  css  js  c++  java
  • 随机生成大小为100的范围是100-1000的不重复的数组

    首先想到的是用Set保证不重复,如果重复就重新生成随机数。。

    但是这样可能复杂度会很高,不稳定。

    面试官问还有什么办法的时候,我真是毫无头绪。

    一面试就智商下线 //说的好像平时在线是的

    QAQ

    查了下题解:生成N个不相等的随机数

    第一个方法是我写的暴力 T^T

    第二个就是用一个数组记录还未用到的数字 然后每次随即下标就好了 这样保证一定是不重复的

    import java.util.HashSet;
    import java.util.Random;
    import java.util.Set;
    
    public class RandomArray {
        
        Random rand = new Random();
        
        public int[] getArray1(int n, int low, int high) {
            int[] arr = new int[n];
            Set<Integer> set = new HashSet<>();
            for (int i = 0; i < n; ++i) {
                int x = randomInt(low, high);
                while (set.contains(x)) {
                    x = randomInt(low, high);
                }
                set.add(x);
                arr[i] = x;
            }
            return arr;
        }
        
        private int randomInt(int low, int high) {
            return rand.nextInt(high - low + 1) + low;
        }
        
        
        public int[] getArray2(int n, int low, int high) {
            int[] arr = new int[n];
            int length = high - low + 1;
            int[] notUseNum = new int[length];
            
            // 先将要生成的数放到数组中  然后每次在数组中随机取一个
            for (int i = 0; i < length; ++i) {
                notUseNum[i] =  i + low;
            }
            
            for (int i = 0; i < n; ++i) {
                // 在数组中随即选取一个数字
                int pos = rand.nextInt(length);
                arr[i] = notUseNum[pos];
                // 把用过的删除  把最后的挪到该位置 这样保证要取的数字位置都是连续的
                notUseNum[pos] = notUseNum[--length];
            }
            
            return arr;
        }
        
        public static void main(String[] args) {
            RandomArray ra = new RandomArray();
            
            int[] arr = ra.getArray1(100, 100, 1000);
            for (int i: arr) 
                System.out.println(i);
            
            int[] arr2 = ra.getArray2(10, 1, 10);
            for (int i: arr2) 
                System.out.println(i);
        }
        
    }
  • 相关阅读:
    CSP2020 T1儒略日 暴力模拟90pts代码
    CSP-S 2019 D1T2括号树
    P3593 [POI2015]TAB
    P5145 漂浮的鸭子
    CH0503 奇数码问题
    [NOIP2012]国王游戏 -高精度-贪心-
    费解的开关
    P1040 加分二叉树
    初步学习线段树
    P2758 编辑距离 简单DP
  • 原文地址:https://www.cnblogs.com/wenruo/p/6636319.html
Copyright © 2011-2022 走看看