add solution(s)
This commit is contained in:
BIN
src/leetcode_23/n1657_minimize_deviation_in_array/img.png
Normal file
BIN
src/leetcode_23/n1657_minimize_deviation_in_array/img.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 118 KiB |
42
src/leetcode_23/n382_linked_list_random_node/Solution.java
Normal file
42
src/leetcode_23/n382_linked_list_random_node/Solution.java
Normal 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package n502_ipo;
|
||||
|
||||
import scala.Int;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
Reference in New Issue
Block a user