算法-[0,99]範圍內隨機數不重複地放入長度爲100的數組

算法-隨機數填充相關問題

1、隨機數填充

這個題目看着比較特別,就記錄一下

題目是這樣的:

[0,99]範圍內隨機數不重複地放入長度爲100的數組

剛開始想是無處下手的,其實利用HashSet/HashMap的話其實時間複雜度是無窮大。

我們只能先生成數據,然後打亂數據的排序。

    public static void main(String[] args) {
        int[] nums=new int[100];
        for (int i=0;i<nums.length;i++){//生成數據
            nums[i]=i;
        }
        Random ran=new Random();
        for (int i=0;i<nums.length;i++){
            int j=ran.nextInt(nums.length);//打亂順序
            swap(nums,i,j);
        }
        for (int i:nums){
            System.out.print(i+"\t");
        }
    }
    public static void swap(int nums[],int i,int j){
        int temp=nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }

2、打亂數組

384. 打亂數組

打亂一個沒有重複元素的數組。

示例:

// 以數字集合 1, 2 和 3 初始化數組。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// 打亂數組 [1,2,3] 並返回結果。任何 [1,2,3]的排列返回的概率應該相同。
solution.shuffle();

// 重設數組到它的初始狀態[1,2,3]。
solution.reset();

// 隨機返回數組[1,2,3]打亂後的結果。
solution.shuffle();

本題和上面題目幾乎一樣,我們可以採用相同的方式打亂順序

class Solution {
    private int[] backup;
    private int[] nums;
    public Solution(int[] nums) {
        this.nums=nums;
        backup=new int[nums.length];
        for(int i=0;i<nums.length;i++){
            backup[i]=nums[i];
        }

    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        for(int i=0;i<backup.length;i++){
            nums[i]=backup[i];
        }
        return backup;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        Random ran=new Random();
        for(int i=0;i<nums.length;i++){
            int j=ran.nextInt(backup.length);
            swap(nums,i,j);
        }
        return nums;
    }

    private void swap(int[] nums,int i,int j){
        int temp=nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章