用于推送,弹出和查找最小值的自定义数据结构

问题描述

| 有人问我以下与A公司的面试问题: 问题:设计一个数据结构,其中要进行3个操作,即推入,弹出并找到最小值。您应该在固定时间内执行所有这3个操作。 我的回答:我将使用一个链表,在该链表中,我可以在固定时间内进行插入和删除操作,并且会使用额外的内存来存储最小值。 他提出了第二个问题,说,如果您弹出最低限度,怎么找到第二最低限度?再次,在恒定的时间。 你会告诉他什么?     

解决方法

如果您像上面说的那样做一个链表,又存储了当前的最小值,该怎么办。当您添加新数字时,它将查看前一个最小值,如果当前值较低,则将当前最小值更改为当前值。 例如,假设您有数据:3、6、4、2、7、1。那么列表就是这样 值|分钟 3 | 3-> 6 | 3-> 4 | 3-> 2 | 2-> 7 | 2-> 1 | 1 在您添加/删除项目时,这些记录都会记录下来。 编辑: 我提到往回走,可能是这样的: 1 | 1-> 7 | 2-> 2 | 2-> 4 | 3-> 6 | 3-> 3 | 3 然后,您将不需要“页脚”。     ,最小筹码量问题-http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Practice_Questions_Person_A.pdf 从PDF: 问题:最小堆栈 描述支持\“ push \”,\“ pop \”和\“ find minimum \”的堆栈数据结构 操作。 \“ Find minimum \”返回堆栈中的最小元素。 好的答案:存储两个堆栈,其中一个包含堆栈中的所有项目 其中一个是一堆极小值。要推送元素,请将其推送到第一个 堆。检查它是否小于第二个堆栈的顶部项目;如果是这样,推 它到第二个堆栈。要弹出一个项目,请从第一个堆栈中弹出它。如果是顶部 第二个堆栈的元素,将其从第二个堆栈中弹出。寻找最低 元素,只需将元素返回第二个堆栈的顶部即可。每次操作 需要O(1)时间。     ,让每个节点保留对先前最小项目的另一个引用。因此,当您弹出最小的项目时,可以还原以前的最小项目。因为您只能推送和弹出,所以它将是正确的节点。     ,这是实现Bryce Siedschlaw给出的上述算法的C代码:
#include<stdio.h>
#include<stdlib.h>

#define minimumOf(a,b) (a<b) ? a : b;

struct node{
    int data;
    struct node* next;
    int min;
};

void push(struct node **head_ref,int new_data){
    struct node* new_node = (struct node *)malloc(sizeof(struct node));
    new_node->data = new_data;

    if(*head_ref == NULL)
        new_node->min = new_data;
    else
        new_node->min = minimumOf(new_data,(*head_ref)->min);

    new_node->next = *head_ref;
    *head_ref = new_node;
}

int minimum(struct node *head){
    return head->min;
}

int pop(struct node **head_ref){
    int pop_data = (*head_ref)->data;
    (*head_ref) = (*head_ref)->next;
    return pop_data;
}

void printList(node *head){
    while(head != NULL){
        printf(\"%d->\",head->data);
        head = head->next;
    }
    printf(\"\\b\\n\");
}

int main(){
    struct node* a = NULL;

    push(&a,100);
    push(&a,24);
    push(&a,16);
    push(&a,19);
    push(&a,50);
    printList(a);
    printf(\"Minimum is:%d\\n\",minimum(a));
    printf(\"Popped:%d\\n\",pop(&a));
    printf(\"Minimum is:%d\\n\",minimum(a));
}
    ,这会让您发狂-http://algods-cracker.blogspot.in/2011/09/design-data-structure-which-supports.html