隨機列印0-100的全部數字並且不可重複,時間複雜度為O(n)

小帥學java發表於2020-12-30
import java.util.*;

public class Test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Random a = new Random();
		LinkedHashSet<Integer> b = new LinkedHashSet<>();
		int sum = 0;
		while (b.size() < 100) {
			int c = a.nextInt(101);// [0,101)
			b.add(c);
			sum += 1;
		}
		System.out.println(sum);// O(n) 列印了多少次
		Iterator<Integer> iterator = b.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	}

}

 

相關文章