add solution(s)

This commit is contained in:
Viktar Arlou
2023-03-10 12:39:19 +01:00
parent cf92abc21b
commit 2ecb0ad15b
3 changed files with 42 additions and 2 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

View File

@@ -0,0 +1,42 @@
package n382_linked_list_random_node;
import util.ListNode;
public class Solution {
private final ListNode root;
private int size = 0;
public Solution(ListNode head) {
this.root = head;
while (head!=null) {size++;head = head.next;}
}
public int getRandom() {
var rnd = Math.random();
var res = root;
int nIdx = (int)Math.ceil(size * rnd) - 1;
for (int i = 0; i < nIdx; i++) res = res.next;
return res.val;
}
public int getRandomSlowCorrect() {
var rnd = Math.random();
var iter = root;
var res = root;
int size = 1, lastIdx= 1;
while (iter != null) {
int nIdx = (int)Math.ceil(size * rnd);
if (lastIdx< nIdx) {res = res.next!=null ? res.next : res;lastIdx =nIdx;}
size++;
iter = iter.next;
}
return res.val;
}
public static void main(String[] args) {
var s = new Solution(ListNode.of(1, 2, 3));
for (int i = 0; i < 3; i++) {
System.out.println(s.getRandom());
}
}
}

View File

@@ -1,7 +1,5 @@
package n502_ipo;
import scala.Int;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;