File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ import java.util.Random
2+
3+ /* *
4+ * Given a singly linked list, return a random node's value from the linked list.
5+ * Each node must have the same probability of being chosen.
6+ *
7+ * Implement the Solution class:
8+ * Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
9+ * int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
10+ *
11+ * Constraints:
12+ * The number of nodes in the linked list will be in the range [1, 10^4].
13+ * -10^4 <= Node.val <= 10^4
14+ * At most 104 calls will be made to getRandom.
15+ *
16+ *
17+ * Follow up:
18+ * What if the linked list is extremely large and its length is unknown to you?
19+ * Could you solve this efficiently without using extra space?
20+ */
21+
22+ fun main () {
23+ val head = ListNode (1 , ListNode (2 , ListNode (3 )))
24+
25+ val result = Solution (head).getRandom()
26+
27+ println (result)
28+ }
29+
30+ class ListNode (
31+ var `val `: Int ,
32+ var next : ListNode ? = null
33+ )
34+
35+ class Solution (head : ListNode ? ) {
36+ private val values = mutableListOf<Int >()
37+
38+ // 시간 복잡도 : O(N)
39+ // 공간 복잡도 : O(N)
40+ init {
41+ var current = head
42+
43+ while (current != null ) {
44+ values.add(current.`val `)
45+ current = current.next
46+ }
47+ }
48+
49+ // 시간 복잡도 : O(1)
50+ // 공간 복잡도 : O(N)
51+ fun getRandom (): Int {
52+ return values[Random ().nextInt(values.size)]
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments