面試題:打亂一個1~100的數組(睡眠算法)

哎!今天遇到一個面試題,騰訊電話一面。當時緊張得腦殼都抽掉了,給了三個方案都不行,並且自我感受都很差。啊,太緊張了,腦殼都不會轉了。面試

題目

題目的大意就是:打亂一個1~100的數組(每一個數打亂的機率要相同)數組

1、等待取票

面試完靜下來想了想,能不能有其餘好的解法,而後第一種想法居然是相似「睡眠排序」。安全

個人思路:去動物園排隊,100我的,去盒子裏取號,根據號碼順序入場。bash

如何設置這個盒子:獲取🎫的規則,隨機生成。dom

public class Main {
    public static void main(String[] args) {
        TicketThread[] tt = new TicketThread[101];  
        for (int i = 1; i < 101; i++) {  
            tt[i] = new TicketThread(i);  
        } 
        for (int i = 1; i < 101; i++) {  
            tt[i].start();  
        }  
    }
}
class TicketThread extends Thread{  
    private int val = 0;  
    int max = 100;
    int min = 0;
    public TicketThread(int val){  
        this.val = val;  
    }  
    public void run(){  
        try {  
            sleep((int) (Math.random()*(max-min)+min));
        } catch (InterruptedException e) {       
            e.printStackTrace();  
        }  
        System.out.println(val);  
    }  
} 
複製代碼

2、交換門票

第二種方法我回會宿舍的路上想到的,就是「交換門票」。this

思路:按順序發了門票,而後閉着眼睛兩兩交換,每一個人必須主動交換一次。(包括與本身)spa

如何交換:生成1—100的隨機數,和站在那的人交換。(交換的是兩個位置的人手中的票,不是交換對應的號碼)code

public class Main {
    public static void main(String[] args) {
        int[] tt = new int[100];
        int max = 100;
        int min = 0;
        for(int i = 0;i < tt.length;){
            tt[i] = ++i;
        }
        for(int i = 0;i < tt.length;++i){
            int ran = (int) (Math.random()*(max-min)+min);
            int temp = tt[i];
            tt[i] = tt[ran];
            tt[ran] = temp;
        }
        for(int x : tt){
            System.out.println(x); 
        }
    }
}
複製代碼

總結一下:面試真的超級緊張,面試者的思考不會太發散,老是在本身的安全範圍內搜索答案,哎,多多參加點面試,鍛鍊鍛鍊。上次視頻面試有點頭暈,還好撐住了那幾秒。視頻

相關文章
相關標籤/搜索