mirror of
				https://gitee.com/coder-xiaomo/leetcode-problemset
				synced 2025-11-04 03:33:12 +08:00 
			
		
		
		
	
		
			
				
	
	
		
			36 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
			
		
		
	
	
			36 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
<p>Given an integer array <code>nums</code> with possible <strong>duplicates</strong>, randomly output the index of a given <code>target</code> number. You can assume that the given target number must exist in the array.</p>
 | 
						|
 | 
						|
<p>Implement the <code>Solution</code> class:</p>
 | 
						|
 | 
						|
<ul>
 | 
						|
	<li><code>Solution(int[] nums)</code> Initializes the object with the array <code>nums</code>.</li>
 | 
						|
	<li><code>int pick(int target)</code> Picks a random index <code>i</code> from <code>nums</code> where <code>nums[i] == target</code>. If there are multiple valid i's, then each index should have an equal probability of returning.</li>
 | 
						|
</ul>
 | 
						|
 | 
						|
<p> </p>
 | 
						|
<p><strong class="example">Example 1:</strong></p>
 | 
						|
 | 
						|
<pre>
 | 
						|
<strong>Input</strong>
 | 
						|
["Solution", "pick", "pick", "pick"]
 | 
						|
[[[1, 2, 3, 3, 3]], [3], [1], [3]]
 | 
						|
<strong>Output</strong>
 | 
						|
[null, 4, 0, 2]
 | 
						|
 | 
						|
<strong>Explanation</strong>
 | 
						|
Solution solution = new Solution([1, 2, 3, 3, 3]);
 | 
						|
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
 | 
						|
solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.
 | 
						|
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
 | 
						|
</pre>
 | 
						|
 | 
						|
<p> </p>
 | 
						|
<p><strong>Constraints:</strong></p>
 | 
						|
 | 
						|
<ul>
 | 
						|
	<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
 | 
						|
	<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
 | 
						|
	<li><code>target</code> is an integer from <code>nums</code>.</li>
 | 
						|
	<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>
 | 
						|
</ul>
 |