有效搜索元素的方法

最近我接受了一次采访,他们问我一个“搜索”的问题。
问题是:

Assume there is an array of (positive) integers, of which each element is either +1 or -1 compared to its adjacent elements.

Example:

06000

Now search for 7 and return its position.

我给了这个答案:

Store the values in a temporary array, sort them, and then apply binary search.

If the element is found, return its position in the temporary array.
(If the number is occurring twice then return its first occurrence)

但是,他们似乎不满意这个答案。

什么是正确的答案?

你可以做一个往往大于1的步骤的线性搜索。关键的观察是,如果例如。 array [i] == 4和7尚未出现,则下一个候选7是在索引i 3.使用while循环,它重复直接到下一个可行候选。

这里是一个实现,略有一般化。它在数组中找到k的第一次出现(受限于= 1限制),如果不出现,则为-1:

#include <stdio.h>
#include <stdlib.h>

int first_occurence(int k, int array[], int n);

int main(void){
    int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8};
    printf("7 first occurs at index %d\n",first_occurence(7,a,15));
    printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15));
    return 0;
}

int first_occurence(int k, int array[], int n){
    int i = 0;
    while(i < n){
        if(array[i] == k) return i;
        i += abs(k-array[i]);
    }
    return -1;
}

输出:

7 first occurs at index 11
but 9 first "occurs" at index -1
http://stackoverflow.com/questions/34481582/efficient-way-to-search-an-element

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:有效搜索元素的方法