Random.nextInt前增量与后增量

时间:2019-07-05 09:34:06

标签: java

我正在研究LeetCode 398.Random Pick Index。当我使用预增量nextInt(++ count)时,代码正在通过测试用例,但是当我使用nextInt(count + 1)并随后递增计数时,则测试用例未通过。我不确定为什么帖子增量不起作用

working code

public int pick(int target) {
        int result = -1;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != target)
                continue;
            if (rnd.nextInt(++count) == 0){
                result = i;
            }
        }

        return result;
    }
Not working code

public int pick(int target) {
        int result = -1;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != target)
                continue;
            if (rnd.nextInt(count+1) == 0){
                result = i;
                count++;
            }
        }

        return result;
    }

0 个答案:

没有答案