果然还是得研究有难度的题目,才会收获更大
public class Solution {
Map<Integer,String> saveOneToNHashMap=new HashMap<Integer,String>();
public Solution(int[] nums){
for(int i=0;i<nums.length;i++){
if(saveOneToNHashMap.containsKey(nums[i])){
String indexString=saveOneToNHashMap.get(nums[i]);
saveOneToNHashMap.put(nums[i],indexString+i);
}else{
saveOneToNHashMap.put(nums[i],i+"");
}
}
}
public int pick(int target){
String indexStr=saveOneToNHashMap.get(target);
int index=new Random().nextInt(indexStr.length());
char resultIndex=indexStr.charAt(index);
return (int)resultIndex-(int)'0';
}
}
这个是我一开始的做法,但是String的长度是有限制的,一个字符串的长度大于65535就会报错,
在相同思路的做法下,官方的解题思路是将String换成了List<Integer>.
class Solution {
Map<Integer, List<Integer>> pos;
Random random;
public Solution(int[] nums) {
pos = new HashMap<Integer, List<Integer>>();
random = new Random();
for (int i = 0; i < nums.length; ++i) {
pos.putIfAbsent(nums[i], new ArrayList<Integer>());
pos.get(nums[i]).add(i);
}
}
public int pick(int target) {
List<Integer> indices = pos.get(target);
return indices.get(random.nextInt(indices.size()));
}
}
|