398.Random Pick Index
Tags: [random], [trick]
Link: https://leetcode.com/problems/random-pick-index/?tab=Description
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
Solution:
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
indexes = []
for i in xrange(len(self.nums)):
if self.nums[i] == target:
indexes.append(i)
rand_index = random.randint(0, len(indexes) - 1)
return indexes[rand_index]
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
Note:
- Time complexity = O(n), n is the number of elements of the given array.
- In Python, random.randint(x, y) will generate a random int in the range [x, y], both x and y are inclusive.
- In Python, random.randrange(x, y) will generate a random int in the range [x, y), x is inclusive, but y is exclusive.
Memory Limited Exceeded
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.num_index_map = {}
for i in xrange(len(nums)):
num = nums[i]
if num in self.num_index_map:
self.num_index_map[num].append(i)
else:
self.num_index_map[num] = [i];
def pick(self, target):
"""
:type target: int
:rtype: int
"""
indexes = self.num_index_map[target]
rand_index = random.randint(0, len(indexes) - 1)
return indexes[rand_index]
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
Note:
- If we do many times 'pick' operations, this solution is faster, but it uses more memory than the first accepted solution.