【发布时间】:2019-08-05 01:00:59
【问题描述】:
我有大量的整数数组(大小在 10'000 和 1'400'000 之间)。我想让第一个整数更大的值。该值永远不会在数组中。
我已经寻找了各种解决方案,但我只找到了:
- 估计每个值的方法,不是为排序列表或数组设计的(具有 O(n) 时间复杂度)。
- 递归方法和/或不是为非常大的列表或数组设计的方法(时间复杂度为 O(n) 或更高,但在其他语言中,所以我不确定)。
我设计了自己的方法。这里是:
int findClosestBiggerInt(int value, int[] sortedArray) {
if( sortedArray[0]>value ||
value>sortedArray[sortedArray.length-1] ) // for my application's convenience only. It could also return the last.
return sortedArray[0];
int exp = (int) (Math.log(sortedArray.length)/Math.log(2)),
index = (int) Math.pow(2,exp);
boolean dir; // true = ascend, false = descend.
while(exp>=0){
dir = sortedArray[Math.min(index, sortedArray.length-1)]<value;
exp--;
index = (int)( index+ (dir ? 1 : -1 )*Math.pow(2,exp) );
}
int answer = sortedArray[index];
return answer > value ? answer : sortedArray[index+1];
}
它的时间复杂度为 O(log n)。对于长度为 1'400'000 的数组,它将在 while 块内循环 21 次。不过,我不确定它是否无法改进。
有没有更有效的方法来做到这一点,而不需要外部包的帮助?节省的任何时间都很棒,因为这种计算非常频繁。
【问题讨论】:
-
简单的二分搜索有什么问题?
-
我不确定。不是对数组中的特定值进行二分查找吗?
-
更多关于代码审查的话题。你应该在那里问。
-
但是,二分查找可用于解决更广泛的问题,例如在数组中找到相对于目标的下一个最小或下一个最大元素,即使它不存在来自数组。来自维基百科。
-
另外,你需要保留重复的能力吗?
TreeSet已内置此功能。