java - 获取双精度数组中的唯一元素 - Java
问题描述
如何获取在双数组中出现一次的元素?下面是我尝试过的,执行时间不可接受。这将针对非常庞大的数组运行。只能有一个独特的元素。
public static double getUnique(double arr[]) {
double res = 0.0;
for (int i = 0; i < arr.length; i++){
res = arr[i];
int count = 0;
for (int j = 0; j < arr.length; j++){
if (res == arr[j]){
count ++;
}
if(j == arr.length - 1){
if(count == 1){
return res;
}
}
}
}
return res;
}
解决方案
你可以做这样的事情,这将计算 a 中的所有双打HashMap
并返回第一个double
出现的情况1
:
public static double getUniqueMine(double arr[]) {
// Keep track of the occurances of doubles
HashMap<Double, Integer> doubleOccurances = new HashMap<>();
// Loop through all doubles
for(double d : arr) {
// Increment double count
doubleOccurances.merge(d, 1, Integer::sum);
}
// Return the first item where the count is 1
for(Entry<Double, Integer> values : doubleOccurances.entrySet()) {
if(values.getValue() == 1) {
return values.getKey();
}
}
return 0.0;
}
推荐阅读
- javascript - 你能告诉我他们的代码之间是否有任何区别。如果他们是,那么背后的原因是什么?
- webpack - Electron 在开发和构建的应用程序中伪造静态资产
- assembly - GDB中寄存器偏移1的可能原因是什么?
- r - R ggplot2 stat_density_2d 具有“..level..”功能,还有哪些其他功能可用?
- nginx - 我不断收到一个空的任务列表 APScheduler
- python - 基于文本的游戏统计
- php - $this 的快速修复不能在静态方法中使用?
- docker - HTTPS 加载但没有网络聊天聊天机器人
- jquery - 节点 Js - Express - CSURF:“无效的 csrf 令牌”
- python - 具体张量分解