9. Math

获得随机数 Shuffle an array

  • 这题的关键在于要设计一个shuffle算法使得每个位置的数被shuffle的概率相同

  • 于是就有了int i = random.nextInt(j + 1)的这个trick

  • int index = random.nextInt(i + 1);

  • nextInt返回的是[0,i+1)的整数

  • 所以不可以是random.nextInt(0, i),设想一共就两个数(6,4)

  • 如果是nextInt(0,i) i start from 1, 这样的话4就只可能在[0,0]区间内变换,就只有这一种shuffle可能了

public class Solution {
    private int[] nums = null;
    private Random random = null;
    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return Arrays.copyOf(nums, nums.length);
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] arr = Arrays.copyOf(nums, nums.length);
        for(int i = 1; i < arr.length; i++){
            int index = random.nextInt(i + 1);
            swap(arr, i, index);
        }
        return arr;
    }
    private void swap(int[] nums, int a, int b){
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}

Count Primes

  • 给定一个数n, 求比n小的素数的个数

  • 建立一个boolean[] notPrime = new boolean[n]

  • 然后每找到一个prime number, cnt++, 并把它的所有的倍数都设成notPrime = true

Reverse Integer

  • 本身不难

  • 注意integer overflow的edge case

Last updated