LeetCode#398 Random Pick Index
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:
1 | int[] nums = new int[] {1,2,3,3,3}; |
解题思路
本来想在构造方法里建表的,但是note里说了
Solution that uses too much extra space will not pass the judge.
只好每个都算一遍了,Solution里把传进来的数组存到类的类成员里,然后在pick方法里遍历数组,并把target出现的位置索引都记下来,随机输出一个就OK了
解题代码【.CPP】
1 | class Solution { |