Skip to content

Commit bc7b71f

Browse files
authored
Merge pull request #510 from 0chnxxx/0chnxxx/ltc/398
2 parents 96e64ba + 00c423f commit bc7b71f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Given an integer array nums with possible duplicates, randomly output the index of a given target number.
3+
* You can assume that the given target number must exist in the array.
4+
*
5+
* Implement the Solution class:
6+
* Solution(int[] nums) Initializes the object with the array nums.
7+
* int pick(int target) Picks a random index i from nums where nums[i] == target.
8+
* If there are multiple valid i's, then each index should have an equal probability of returning.
9+
*
10+
* Constraints:
11+
* 1 <= nums.length <= 2 * 10^4
12+
* -2^31 <= nums[i] <= 2^31 - 1
13+
* target is an integer from nums.
14+
* At most 10^4 calls will be made to pick.
15+
*/
16+
17+
fun main() {
18+
val solution = Solution(intArrayOf(1, 2, 3, 3, 3));
19+
println(solution.pick(3))
20+
println(solution.pick(1))
21+
println(solution.pick(3))
22+
}
23+
24+
class Solution(private val nums: IntArray) {
25+
// 시간 복잡도 : O(N)
26+
// 공간 복잡도 : O(1)
27+
fun pick(target: Int): Int {
28+
var result = -1
29+
var count = 0
30+
31+
for (i in nums.indices) {
32+
if (nums[i] == target) {
33+
count++
34+
35+
if ((0 until count).random() == 0) {
36+
result = i
37+
}
38+
}
39+
}
40+
41+
return result
42+
}
43+
}

0 commit comments

Comments
 (0)