在数组

时间:2016-12-23 01:02:26

标签: java arrays algorithm

对于具有O(n)效率的以下问题,是否有解决方案?

  

您需要在数组中找到一个单元格,使其前面的所有数字都低于它,并且它之后的所有数字都高于它。你应该忽略第一个和最后一个单元格。

例如,请考虑以下列表:

1, 3, 2, 6, 5, 7, 9, 8, 10, 8, 11

在这种情况下,答案将是索引7的数字5

5 个答案:

答案 0 :(得分:31)

这是一个 O(n),是Python中的一个通过解决方案。端口到Java是微不足道的:

import random
A = [random.randint(1, 10) for i in range(0, 5)] # Generate list of size 5.
max_seen = A[0]
candidate = None
for i in range(1,len(A)):
  if candidate is None:
    if A[i] > max_seen:
      candidate = i
  else:
    if A[i] <= A[candidate]:
      candidate = None
  max_seen = max(max_seen, A[i])

print("Given %s " % (A,))
if candidate is not None and candidate != len(A)-1: # Ignore the last element as per spec.
  print("found: value=%d; index=%d\n" % (A[candidate], candidate))
else:
  print("not found")

您需要运行几次才能生成实际满足条件的列表。

<强>描述

重述目标:找到数组 A 中的元素的索引 i ,使得 all A [j],j&lt; i =&gt; A [j]&lt; A [i]和所有A [k],k> i =&gt; A [k]&gt; A [i] 。第一个这样的元素是一个这样的元素,所以我们只找到第一个元素。

给定索引 x ,如果 x 满足上述条件,则 A [x]&gt; A [0..x-1]和A [x]&lt; A [X + 1..A.length] 。只需验证给定 x 的两个约束即可。注意 A [x]&gt; A [0..x-1]&lt; =&gt; A [x]&gt; MAX(A [0..X-1])。因此,我们保持到目前为止看到的最大值,找到满足条件1的第一个 x ,并遍历数组验证条件2得到满足。如果条件2未被验证,我们知道下一个可能的候选者超出当前索引 y ,因为 A [x..y-1]&gt; A [x] =&gt; A [y]&lt; A [x..y-1] ,并且大于目前为止看到的最大值。

答案 1 :(得分:16)

是的,肯定可以在O(n)时间内完成 。接下来是几种方法。

第一个更有用的是找到所有候选单元格。对数据进行单O(n)次传递,每个单元格设置两个额外项目,因此O(n)空间(通过交易空间可以解决一小部分优化问题)。

每个单元格需要计算的两个项目是左边的最高值和右边的最小值。第一个通道为所有单元格设置这些项目,最后一个单元格没有意义(显然是伪代码):

# Set current values.

highLeftVal = cell[0]
lowRightVal = cell[cell.lastIndex]

# For running right and left through array.

rightIdx = cell.lastIndex
for each leftIdx 1 thru cell.lastIndex inclusive:
    # Left index done by loop, right one manually.

    rightIdx = rightIdx - 1

    # Store current values and update.

    highLeft[leftIdx] = highLeftVal
    if cell[leftIdx] > highLeftVal: highLeftVal = cell[leftIdx]

    lowRight[rightIdx] = lowRightVal
    if cell[rightIdx] < lowRightVal: lowRightVal = cell[rightIdx]

然后检查每个单元格(第一个和最后一个单元格)以确保该值都大于(根据您的问题,此答案假定“更高/更低”是 literal < / em>,而不是“大于/小于或等于”)左边的最高值和右边的最低值:

for each idx 1 thru cell.lastIndex-1 inclusive:
    if cell[idx] > highLeft[idx] and cell[idx] < lowRight[idx]
        print "Found value ", cell[idx], " at index ", idx

您可以在下面看到初始传递的结果:

highLeft:   -  1  3  3  6  6  7  9  9 10 10
cells   :   1  3  2  6  5  7  9  8 10  8 11
lowRight:   2  2  5  5  7  8  8  8  8 11  -
                           ^

候选单元格,其值是针对其上方和下方的两个值进行排序(不包括),是7标记为^

现在请记住,这是一个相对易于理解的解决方案,可以找到满足约束条件的多个项目。鉴于您只需要一个项,可以获得更好的性能(尽管它仍然是O(n))。

基本思路是从左到右遍历数组,对于每个单元格,检查左边的所有内容是否较低,右边的所有内容都是较高的。

第一点很简单,因为通过从左到右遍历,您可以记住遇到的最高值。第二点似乎涉及以某种方式展望未来,但有一个技巧可以用来避免这种“时间体操”。

这个想法是保持当前单元格左侧的最高值和当前答案的索引(最初设置为哨兵值)。

如果当前答案是哨兵值,则选择满足“大于左边一切”的第一个单元作为可能的答案。

而且,只要情况仍然如此,那就是您选择的单元格。但是,只要您在右侧找到小于或等于它的那个,它就不再有效,因此您将其丢弃并再次开始搜索。

此搜索从当前点开始,而不是在开始时,因为:

  • 当前答案之后的所有内容,但不包括此(小于或等于)单元格高于当前答案,否则您将找到更小或相等的单元格;和
  • 因此,
  • 此单元格必须小于或等于该范围内的每个单元格,因为它小于或等于当前答案;因此
  • 该范围内的
  • 没有单元格有效,它们全部大于或等于此范围。

完成非最终项目的处理后,您的答案将是哨兵或几乎满足约束条件的单元格。

我说“差不多”,因为需要进行最后一次检查以确保最终项目大于它,因为您在遍历过程中没有对该项目执行任何检查。

因此,该野兽的伪代码如下:

# Store max on left and start with sentinel.

maxToLeft = cell[0]
answer = -1

for checking = 1 to cell.lastIndex-1 inclusive:
    switch on answer:
        # Save if currently sentinel and item valid.
        case -1:
            if cell[checking] > maxToLeft:
                answer = checking

        # Set back to sentinel if saved answer is now invalid.
        otherwise:
            if cell[answer] >= cell[checking]:
                answer = -1

    # Ensure we have updated max on left.

    if cell[checking] > maxToLeft:
        maxToLeft = cell[checking]

# Final check against last cell.

if answer != -1:
    if cell[cell.lastIndex] <= cell[answer]:
        answer = -1

由于我的伪代码(严重地)基于Python,因此提供一个更具体的代码实例是一件相当简单的事情。首先,“找到所有可能性”选项:

cell = [1, 3, 2, 6, 5, 7, 9, 8, 10, 8, 11]

highLeft = [0] * len(cell)
lowRight = [0] * len(cell)

highLeftVal = cell[0]
lowRightVal = cell[len(cell)-1]

rightIdx = len(cell) - 1
for leftIdx in range(1, len(cell)):
    rightIdx = rightIdx - 1

    highLeft[leftIdx] = highLeftVal
    if cell[leftIdx] > highLeftVal: highLeftVal = cell[leftIdx]

    lowRight[rightIdx] = lowRightVal
    if cell[rightIdx] < lowRightVal: lowRightVal = cell[rightIdx]

print(highLeft)
print(cell)
print(lowRight)

for idx in range(1, len(cell) - 1):
    if cell[idx] > highLeft[idx] and cell[idx] < lowRight[idx]:
        print("Found value", cell[idx], "at index", idx)

第二个更有效的选择,但只能找到一种可能性:

cell = [1, 3, 2, 6, 5, 7, 9, 8, 10, 8, 11]
maxToLeft = cell[0]
answer = -1
for checking in range(1, len(cell) - 1):
    if answer == -1:
        if cell[checking] > maxToLeft:
            answer = checking
    else:
        if cell[answer] >=cell[checking]:
            answer = -1
    if cell[checking] > maxToLeft:
        maxToLeft = cell[checking]

if answer != -1:
    if cell[len(cell] - 1] <= cell[answer]:
        answer = -1

if answer == -1:
    print ("Not found")
else:
    print("Found value", cell[answer], "at index", answer);


print(highLeft)
print(cell)
print(lowRight)

for idx in range(1, len(cell) - 1):
    if cell[idx] > highLeft[idx] and cell[idx] < lowRight[idx]:
        print("Found value", cell[idx], "at index", idx)

两者的输出(虽然后一个例子只显示最后一行)基本上显示了伪代码的含义:

[0, 1, 3, 3, 6, 6, 7, 9, 9, 10, 10]
[1, 3, 2, 6, 5, 7, 9, 8, 10, 8, 11]
[2, 2, 5, 5, 7, 8, 8, 8, 8, 11, 0]
Found value 7 at index 5

答案 2 :(得分:5)

创建一个额外的数组,该数组通过在源数组上从左到右计算得出。对于此数组中的任何索引N,该值是在第一个数组中0:N-1之间观察到的最高值。

int arr1 = new int[source.length];
int highest = MIN_INT;
for (int i = 0; i < source.length; i++) {
    arr1[i] = highest;
    if (source[i] > highest) {
        highest = source[i];
    }
}

现在创建一个第二个数组,通过从右到左扫描形成,其中索引N处的任何值表示在N + 1之间看到的最低值:结束

arr2 = new int[source.length];
int lowest = MAX_INT;
for (int i = (source.length-1); i <= 0; i--) {
    arr2[i] = lowest;
    if (source[i] < lowest) {
        lowest = source[i];
    }
}

现在你基本上有三个阵列:

source: 1   3   2   6   5  7   9   8   10   8   11
arr1:   MIN 1   3   3   6  6   7   9    9  10   10
arr2:   2   2   5   5   7  8   8   8    8  11   MAX

现在您只想将所有三个数组扫描在一起,直到找到满足此条件的索引:

arr1[i] < source[i] < arr2[i] 

where:
     0 < i < (source.length-1)

代码:

for (int i = 1; i < (source.length-1); i++) {
    if ((arr1[i] < source[i]) && (source[i] < arr2[i])) {
        return i; // or return source[i]
    }
}

这是O(N)时间。

答案 3 :(得分:3)

我使用c的答案中的算法在S.Pinkus中编写了一个实现,并提供了调试信息。

代码

<强> find_mid_num.c:

/**
 * Problem:
 *  there is an array of number, find an element which is larer than elements before it, and smaller than elements after it,
 *  refer:  http://stackoverflow.com/questions/41293848
 * 
 * Solution:
 *  loop through array, remember max value of previous loopped elements, compare it to next element, to check whether the first condition is met,
 *  when found an element met the first condition, then loop elements after it to see whether second condition is met,
 *  if found, then that's it; if not found, say at position 'y' the condition is broken, then the next candidate must be after y, thus resume the loop from element after y,
 *  until found one or end of array,
 * 
 * @author Eric Wang
 * @date 2016-12-23 17:08
 */
#include <stdio.h>

// find first matched number, return its index on found, or -1 if not found,
extern int findFirstMidNum(int *arr, int len);

int findFirstMidNum(int *arr, int len) {
    int i=0, j;
    int max=arr[0];

    while(i < len) {
        printf("\n");
        if(arr[i] <= max) {
            printf("give up [%d]-th element {%d}, 1st condition not met\n", i, arr[i]);
            i++;
            continue;
        }
        max = arr[i]; // update max,

        printf("checking [%d]-th element {%d}, for 2nd condition\n", i, arr[i]);
        j = i+1;
        while(j < len) {
            if(arr[j] <= max) {
                printf("give up [%d]-th element {%d}, 2nd condition not met\n", i, arr[i]);
                break;
            }
            j++;
        }
        printf("position after 2nd check:\ti = %d, j = %d\n", i, j);

        if(j==len && j>i+1) {
            return i;
        } else {
            max = arr[j-1]; // adjust max before jump,
            i = j+1; // jump
            printf("position adjust to [%d], max adjust to value {%d}, after 2nd check\n", i, arr[j-1]);
        }
    }

    return -1;
}

int main() {
    int arr[] = {1, 3, 2, 6, 5, 7, 9, 8, 10, 8, 11};
    int len = sizeof(arr)/sizeof(arr[0]);
    printf("\n============ Input array ============\n");
    printf("size:\t%d\n", len);
    printf("elements:\t{");

    int i;
    for(i=0; i<len; i++) {
        printf("%d, ", arr[i]);
    }
    printf("}\n\n");

    printf("\n============ Running info ============\n");
    int pos = findFirstMidNum(arr, len);

    printf("\n============ Final result============\n");
    if (pos < 0) {
        printf("Element not found.\n");
    } else {
        printf("Element found at:\n\t position [%d], with value: {%d}\n", pos, arr[pos]);
    }
    printf("\n");

    return 0;
}

<强>编译:

gcc -Wall find_mid_num.c

<强>执行:

./a.out

运行结果:

============ Input array ============
size:   11
elements:   {1, 3, 2, 6, 5, 7, 9, 8, 10, 8, 11, }


============ Running info ============

give up [0]-th element {1}, 1st condition not met

checking [1]-th element {3}, for 2nd condition
give up [1]-th element {3}, 2nd condition not met
position after 2nd check:   i = 1, j = 2
position adjust to [3], max adjust to value {3}, after 2nd check

checking [3]-th element {6}, for 2nd condition
give up [3]-th element {6}, 2nd condition not met
position after 2nd check:   i = 3, j = 4
position adjust to [5], max adjust to value {6}, after 2nd check

checking [5]-th element {7}, for 2nd condition
position after 2nd check:   i = 5, j = 11

============ Final result============
Element found at:
     position [5], with value: {7}

TODO - 进一步改进:

  • 检查边界元素。
  • 提供各种功能来查找所有这些元素,而不仅仅是第一个。

答案 4 :(得分:0)

时间和空间复杂度都有 O(n),单个数组传递

逻辑:

  1. 查找到目前为止发现的第一个最大和最大最大数量,继续遍历数组,直到找到小于first_max的值。
  2. 如果你这样做,那么在此之前保留first_max和所有元素,因为所有这些元素都超过了我当前找到的元素。
  3. 现在选择first_max,使下一个值大于我们一直找到的overall_max。
  4. 代码:

    // int[] arr = { 10, 11, 1, 2, 12, 13, 14};
    int[] arr = {  1, 3, 2, 6, 5, 7, 9, 8, 10, 8, 11};
    Integer firstMax = null;
    Integer overallMax = null;
    
    for (int i = 1; i < arr.length - 1; i++) {
        int currentElement = arr[i];
        if (firstMax == null) {
            if (overallMax == null) {
                firstMax = currentElement;
            } else if (overallMax != null && currentElement > overallMax) {
                firstMax = currentElement;
            }
        }
        if (overallMax == null || currentElement > overallMax) {
            overallMax = currentElement;
        }
        if (firstMax != null && currentElement < firstMax) {
            // We found a smaller element, so all max found so far is useless. Start fresh.
            firstMax = null;
        }
    }
    
    System.out.println(firstMax);
    

    PS:根据我的分析,我觉得这应该足够了,适用于所有情况。不确定是否遗漏了任何案件。