代码之家  ›  专栏  ›  技术社区  ›  JOSI

求职面试的基本内容-使用链表、数组

  •  0
  • JOSI  · 技术社区  · 8 年前

    我在一次面试中遇到了这个问题,但我解决不了。
    我想我真的很紧张,因为看起来没那么难。

    Arr是给定的整数数组,大小为n。Sol是给定的空数组, 尺寸n。

    对于每个i(i从0到n-1),必须在Sol[i]中输入索引 在Arr中,最接近的元素出现在左侧,即较小的元素 比Arr【i】高。含义:Sol[i]=max{j | j<i;Arr[j]<Arr[i]}。如果 没有这样的索引,put-1。

    例如:Arr为[5,7,9,2,8,11,16,10,12]Sol为 [-1,0,1,-1,3,4,5,4,7]

    时间复杂度:o(n)空间复杂度:o(n)

    我试图从头到尾扫描阵列,但不知道如何继续。

    我被要求只使用数组和链表。 我有10分钟的时间来解决它,所以我想这并不难。

    非常感谢!!

    2 回复  |  直到 8 年前
        1
  •  1
  •   Michael Burr    8 年前

    请注意,对于长度为<2有一些琐碎的解决方案。此伪代码假定Arr[]的长度为>=2.

    int Arr[] = {5,7,9,2,8,11,16,10,12};
    int Sol[] = new int[9];
    
    Stack<int> undecided;   // or a stack implemented using a linked list
    
    Sol[0] = -1;    // this is a given
    
    for(int i = Arr.length() - 1; i != 0; --i) {
        undecided.push(i); // we haven't found a smaller value for this Arr[i] item yet
                           // note that all the items already on the stack (if any)
                           // are smaller than the value of Arr[i] or they would have
                           // been popped off in a previous iteration of the loop
                           // below
    
        while (!undecided.empty() && (Arr[i-1] < Arr[undecided.peek()])) {
            // the value for the item on the undecided stack is
            //  larger than Arr[i-1], so that's the index for 
            //  the item on the undecided stack
            Sol[undecided.peek()] = i-1;
            undecided.pop();
        }
    }
    
    // We've filled in Sol[] for all the items have lesser values to
    //  the left of them.  Whatever is still on the undecided stack
    //  needs to be set to -1 in Sol
    
    while (!undecided.empty()) {
        Sol[undecided.peek()] = -1;
        undecided.pop();
    }
    

    老实说,我不确定我会在10分钟的面试时间内想到这个问题。

    在ideone上可以找到这方面的C++版本。通用域名格式: https://ideone.com/VXC0yq

        2
  •  0
  •   jonhid    8 年前
        int Arr[] = {5,7,9,2,8,11,16,10,12};
        int Sol[] = new int[9];
    
        for(int i = 0; i < Arr.length; i++) {
            int element = Arr[i];
    
            int tmp = -1;
            for(int j = 0 ;j < i; j++) {
                int other = Arr[j];
                if (other < element) {
                    tmp = j;                    
                }
            }
    
            Sol[i] = tmp;           
        }