【问题标题】:Find occurrence of element查找元素的出现
【发布时间】:2014-07-30 14:58:24
【问题描述】:

给定一个数组,其中每个元素与其前一个元素相差 +1/-1,在不使用线性搜索的情况下找到给定(输入)元素的第一次出现(位置),例如:- 让数组 = 4,5,6 ,5,6,7,8,9,10,9,8,9,10,11... 输入 - 10 输出 - 8(第一次出现的 10 在第 8 位)

【问题讨论】:

    标签: arrays search


    【解决方案1】:

    执行此操作的一种简单方法是在数组中向前跳过目标值与当前值之间的差异。因此,在您的示例中,目标是 10。从第一个元素开始,看到 10(目标)和 4(当前值)之间的差异为 6。鉴于任何两个相邻的值只会相差一个,您知道第一次出现的 10 必须是阵列中至少 6 个点。因此,继续前进并重复该过程,直到找到第一个索引。您的代码可能如下所示:

    int find_first_occurrence(int target, int array[])
    {
        int index = 0;
        while (index <= array.count())
        {
            if (array[index] == target)
            {
                 return index;
            }
            index += abs(array[index] - target);
        }
        // Returning -1 would indicate that the target is not in the array
        return -1;
     }
    

    【讨论】:

    • 非常感谢@Aaron Reynolds
    • 如果它解决了你的问题,你应该接受它作为答案。
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多