简体   繁体   English

如何用对数时间算法解决这个问题?

[英]How to solve this with a logarithmic time algorithm?

I came across the following problem: 我遇到以下问题:

Now you a given array of double number of length n (n is known) as double sample[n] , and it is in ascending order (all elements are different). 现在,您将给定的一个长度为n的双精度数的数组称为double sample[n] ,并且该数组按升序排列(所有元素都不同)。 Please write a function with one parameter double num , which return the index of the element in sample[n] which is closest to the parameter num . 请编写一个带有一个参数double num的函数,该函数将返回sample[n]中最接近参数num的元素的索引。 If num is located exactly in the middle of one interval, return the index of the element smaller than it. 如果num恰好位于一个间隔的中间,则返回小于该元素的索引。

Here is my code in Java: 这是我的Java代码:

public int getIndex(double num) {
    if(sample[0] >= num) {return 0;}
    for(int i = 1, i < sample.length; i++) {
        if(sample[i] == num) {return i;}
        else if(sample[i] > num) {
            return (sample[i]-num) < (num-sample[i-1]) ? i : i-1;
        else {continue;}
    }
    return sample.length;
}

It is clearly linear complexity. 显然是线性复杂度。 However, I was told by my teacher that algorithm with O(log n) exists. 但是,我的老师告诉我,存在O(log n)的算法。 Can anyone help me with the coding? 有人可以帮我编码吗?

Your array is sorted, this means you can use binary search . 您的数组已排序,这意味着您可以使用二进制搜索 I have nothing to add to this answer and will not provide you ready code, because it is your responsibility. 我对此没有任何补充,也不会为您提供现成的代码,因为这是您的责任。 The main idea is that you examine middle element of the array and then determine in which direction you should move: first or second half of an array and so on. 主要思想是检查数组的中间元素,然后确定应朝哪个方向移动:数组的前半部分或后半部分,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM