Simple java solution with O(n) time and O(1) space


  • 1
    S

    Each time when we find a num that is equal to target, generate a random number, return the index with the largest random number.

    public class Solution {
    int[] nums;

    public Solution(int[] nums) {
        this.nums = nums;
    }
    
    public int pick(int target) {
        int index = -1;
        double maxResult = 0;
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                double cur = Math.random();
                if (cur >= maxResult) {
                    maxResult = cur;
                    index = i;
                }
            }
        }
        
        return index;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.