数据结构

来源:互联网 发布:linux wget 磁力链接 编辑:程序博客网 时间:2024/05/17 22:48

数据结构

  • 数据结构
    • 最小栈
    • 用栈实现队列
    • 用队列实现栈


最小栈

设计一个栈结构,支持 push, pop, top操作,并能以恒定的时间获取栈中元素的最小值.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.
# Rubyclass MinStack    def initialize        @mins, @stack = [], []    end    def push(x)        @stack.push x        @mins.push x if @mins.empty? or x <= @mins.last    end    def pop        @mins.pop if @stack.pop == @mins.last    end    def top        @stack.last    end    def get_min        @mins.last    endend

使用2个栈,一个栈stack装元素,另一个栈mins装最小值。每出现一个新的最小值,就将之压入mins栈中,当pop stack时,弹出的元素恰好也等于mins的栈顶,那么也pop mins, 保持mins的栈顶始终是stack中元素的最小值。
为什么def push(x) 中 x <= @mins.last要取等号,是因为stack中可能有几个相等的最小值。
Min Stack


用栈实现队列

  • 只能使用标准的栈操作:push to top, peek/pop from top, size, is empty
  • 假设对该队列的操作都是有效的,即不会对空队列pop/peek
class Queue    # Initialize your data structure here.    def initialize        @stack, @temp = [], []    end    # @param {Integer} x    # @return {void}    def push(x)        if @temp.any? then @stack.push @temp.pop until @temp.empty? end        @stack.push x    end    # @return {void}    def pop        if @temp.empty? then @temp.push @stack.pop until @stack.empty? end        @temp.pop    end    # @return {Integer}    def peek        if @temp.empty? then @temp.push @stack.pop until @stack.empty? end        @temp.last    end    # @return {Boolean}    def empty        @stack.empty? and @temp.empty?    endend

基本想法是Queue类的实例持有2个实例变量,分别为stack和temp, 均为array,当做栈来用。仅对stack做push操作,当需要做pop/peek操作时,把栈stack中的元素移入栈temp, 那么temp的top即队列的top,对temp做pop/peek操作。
Implement Queue using Stacks


用队列实现栈

跟上题基本倒过来,不过是把对数组的操作push, pop换成了unshift和shift.

class Stack    # Initialize your data structure here.    def initialize        @q1, @q2 = [], []    end    # @param {Integer} x    # @return {void}    def push(x)        if @q2.any? then @q1.unshift @q2.pop until @q2.empty? end        @q1.push x    end    # @return {void}    def pop        if @q2.empty? then @q2.unshift @q1.shift until @q1.empty? end        @q2.shift    end    # @return {Integer}    def top        if @q2.empty? then @q2.unshift @q1.shift until @q1.empty? end        @q2.first    end    # @return {Boolean}    def empty        @q1.empty? and @q2.empty?    endend

Implement Stack using Queues

0 0
原创粉丝点击