溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java怎么實現(xiàn)隨機不重復(fù)數(shù)字

發(fā)布時間:2020-06-24 13:08:30 來源:億速云 閱讀:174 作者:Leah 欄目:編程語言

java怎么實現(xiàn)隨機不重復(fù)數(shù)字?針對這個問題,這篇文章給出了相對應(yīng)的分析和解答,希望能幫助更多想解決這個問題的朋友找到更加簡單易行的辦法。

為了更好地理解這個題意,我們先來看下具體內(nèi)容:生成一個1-100的隨機數(shù)組,但數(shù)組中的數(shù)字不能重復(fù),即位置是隨機的,但數(shù)組元素不能重復(fù)。

在這里呢,沒有給我們規(guī)定數(shù)組的長度,我們可以讓它是1-100之間的任意長度。

接下來讓我們看一下幾種實現(xiàn)方法并對這幾種方法作個對比。

通常我們會使用ArrayList或數(shù)組來實現(xiàn),先來看下ArrayList實現(xiàn)過程,如下面代碼所示:

import java.util.ArrayList;
import java.util.Random;

/**
 * 使用ArrayList實現(xiàn)
 * @Description: 
 * @File: Demo.java
 * @Date 2012-10-18 下午06:16:55
 * @Version V1.0
 */
public class Demo {
    public static void main(String[] args) {
        Object[] values = new Object[20];
        Random random = new Random();
        ArrayList<Integer> list = new ArrayList<Integer>();

        for(int i = 0; i < values.length;i++){
            int number = random.nextInt(100) + 1;
            
            if(!list.contains(number)){
                list.add(number);
            }
        }
        
        values = list.toArray();
        
        // 遍歷數(shù)組并打印數(shù)據(jù)
        for(int i = 0;i < values.length;i++){
            System.out.print(values[i] + "\t");
            
            if(( i + 1 ) % 10 == 0){
                System.out.println("\n");
            }
        }
    }
}

使用數(shù)組實現(xiàn)的過程如下所示代碼:

import java.util.Random;

/**
 * 使用數(shù)組實現(xiàn)
 * @Description: 

 * @File: Demo4.java

 * @Package None

 * @Author Hanyonglu

 * @Date 2012-10-18 下午06:27:38

 * @Version V1.0
 */
public class Demo4 {
    public static void main(String[] args) {
        int[] values = new int[20];
        Random random = new Random();
        
        for(int i = 0;i < values.length;i++){
            int number = random.nextInt(100) + 1;
            
            for(int j = 0;j <= i;j++){
                if(number != values[j]){
                    values[i]=number;
                }                              
            }
        }
        
        // 遍歷數(shù)組并打印數(shù)據(jù)
        for(int i = 0;i < values.length;i++){
            System.out.print(values[i] + "\t");
            
            if(( i + 1 ) % 10 == 0){
                System.out.println("\n");
            }
        }
    }
}

上面這兩個實現(xiàn)過程效率比較低的。因為在每次添加時都要去遍歷一下當(dāng)前列表中是否存在這個數(shù)字,時間復(fù)雜度是O(N^2)。我們可以這樣思考一下:既然涉及到無重復(fù),我們可以想一下HashSet和HashMap的功能。

HashSet實現(xiàn)Set接口,Set在數(shù)學(xué)上的定義就是無重復(fù),無次序的集合。而HashMap實現(xiàn)Map,也是不允許重復(fù)的Key。這樣我們可以使用HashMap或HashSet來實現(xiàn)。

在使用HashMap實現(xiàn)時,只需要將它的key轉(zhuǎn)化成數(shù)組就Ok了,如下代碼:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.Map.Entry;

/**
 * 使用HashMap實現(xiàn)
 * @Description: 

 * @File: Demo.java

 * @Package None

 * @Author Hanyonglu

 * @Date 2012-10-18 下午06:12:50

 * @Version V1.0
 */
public class Demo {
    public static void main(String[] args) {
        int n = 0;
        Object[] values = new Object[20];
        
        Random random = new Random();
        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
        
        // 生成隨機數(shù)字并存入HashMap
        for(int i = 0;i < values.length;i++){
            int number = random.nextInt(100) + 1;
            hashMap.put(number, i);
        }
        
        // 從HashMap導(dǎo)入數(shù)組
        values = hashMap.keySet().toArray();
        
        // 遍歷數(shù)組并打印數(shù)據(jù)
        for(int i = 0;i < values.length;i++){
            System.out.print(values[i] + "\t");
            
            if(( i + 1 ) % 10 == 0){
                System.out.println("\n");
            }
        }
        
//        Iterator iter = hashMap.entrySet().iterator();
//        // 遍歷HashMap
//        while (iter.hasNext()) {
//            Entry<Integer, Integer> entry = (Entry)iter.next();
//            int key = entry.getKey();
//            n++;
//            
//            System.out.print(key + "\t");
//            
//            if(n % 10 == 0){
//                System.out.println("\n");
//            }
//        }
    }
}

由于HashSet和HashMap的關(guān)系太近了,HashSet在底層就是用HashMap來實現(xiàn)的,只不過沒有Value的集合,只有一個Key的集合,所以也可使用HashSet來實現(xiàn),如下代碼:

import java.util.HashSet;
import java.util.Random;

/**
 * 使用HashSet實現(xiàn)
 * @Description: 

 * @File: Test.java

 * @Package None

 * @Author Hanyonglu

 * @Date 2012-10-18 下午06:11:41

 * @Version V1.0
 */
public class Test {
    public static void main(String[] args) {
        Random random = new Random();
        Object[] values = new Object[20];
        HashSet<Integer> hashSet = new HashSet<Integer>();
        
        // 生成隨機數(shù)字并存入HashSet
        for(int i = 0;i < values.length;i++){
            int number = random.nextInt(100) + 1;
            hashSet.add(number);
        }
        
        values = hashSet.toArray();
        
        // 遍歷數(shù)組并打印數(shù)據(jù)
        for(int i = 0;i < values.length;i++){
            System.out.print(values[i] + "\t");
            
            if(( i + 1 ) % 10 == 0){
                System.out.println("\n");
            }
        }
    }
}

這樣實現(xiàn)效率稍微好些。如果給我們限定了數(shù)組的長度,只需要變換下for循環(huán),設(shè)置成whlie循環(huán)就可以了。如下所示:

import java.util.HashSet;
import java.util.Random;

/**
 * 使用HashSet實現(xiàn)
 * @Description: 

 * @File: Test.java

 * @Package None

 * @Author Hanyonglu

 * @Date 2012-10-18 下午05:11:41

 * @Version V1.0
 */
public class Test {
    public static void main(String[] args) {
        Random random = new Random();
        Object[] values = new Object[20];
        HashSet<Integer> hashSet = new HashSet<Integer>();
        
        // 生成隨機數(shù)字并存入HashSet
        while(hashSet.size() < values.length){
            hashSet.add(random.nextInt(100) + 1);
        }
        
        values = hashSet.toArray();
        
        // 遍歷數(shù)組并打印數(shù)據(jù)
        for(int i = 0;i < values.length;i++){
            System.out.print(values[i] + "\t");
            
            if(( i + 1 ) % 10 == 0){
                System.out.println("\n");
            }
        }
    }
}

以上幾種相比較而言,使用HashMap的效率是比較高的,其實是HashSet,再次是數(shù)組,最后是ArrayList。如果我們生成10000個數(shù)據(jù)將會發(fā)現(xiàn),使用HashMap花費時間是:0.05s,HashSet是0.07s,數(shù)組是:0.20s,而ArrayList是0.25s。有興趣的可以設(shè)置下時間查看一下。

當(dāng)然了,除了使用HashMap實現(xiàn)外,還有其它高效的方法。比如,我們可以把1-100這些數(shù)字存儲在一個數(shù)組中,然后在for循環(huán)中隨機產(chǎn)生兩個下標(biāo),如果這兩個下標(biāo)不相等的話,可以交換數(shù)組中的元素,實現(xiàn)過程如下所示:

import java.util.Random;

/**
 * 隨機調(diào)換位置實現(xiàn)
 * @Description: 

 * @File: Demo4.java

 * @Package None

 * @Author Hanyonglu

 * @Date 2012-10-18 下午06:54:06

 * @Version V1.0
 */
public class Demo4 {
    public static void main(String[] args) {
        int values[] = new int[100];   
        int temp1,temp2,temp3;   
        Random r = new Random();   
        
        for(int i = 0;i < values.length;i++){
            values[i] = i + 1;
        }
        
        //隨機交換values.length次   
        for(int i = 0;i < values.length;i++){   
            temp1 = Math.abs(r.nextInt()) % (values.length-1); //隨機產(chǎn)生一個位置   
            temp2 = Math.abs(r.nextInt()) % (values.length-1); //隨機產(chǎn)生另一個位置   
            
            if(temp1 != temp2){
                temp3 = values[temp1];   
                values[temp1] = values[temp2];   
                values[temp2] = temp3;
            } 
        }   
        
        // 遍歷數(shù)組并打印數(shù)據(jù)
        for(int i = 0;i < 20;i++){
            System.out.print(values[i] + "\t");
            
            if(( i + 1 ) % 10 == 0){
                System.out.println("\n");
            }
        }
    }
}

關(guān)于java實現(xiàn)隨機不重復(fù)數(shù)字的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI