一种不使用set集合或bool标志位或contains方法的无重算法实现【JAVA】版。。。- package com.itheima.test;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Random;
- public class 不重复随机数 {
- public static void main(String[] args) {
- List<Integer> list = doNotRepeat(10, 70, 15);
- for (Integer integer : list) {
- System.out.println(integer);
- }
- }
- public static List<Integer> doNotRepeat(Integer from, Integer to, Integer choose) {
- Integer listSize = to - from + 1;
- List<Integer> list = new LinkedList<Integer>();
- for (int i = from; i <= to; i++) {
- list.add(i);
- }
- Random random = new Random();
- for (int i = 0; i < choose; i++) {
- list.add(list.remove(random.nextInt(listSize - i)));
- }
- return list.subList(listSize - choose, listSize);
- }
- }
复制代码
|
|