🔥 代码随想录笔记-栈和队列篇

168 阅读5分钟

1.用栈实现队列

[232. 用栈实现队列](leetcode.cn/problems/im…

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

你 只能 使用标准的栈操作 —— 也就是只有push to top, peek/pop from top, size,is empty操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例1

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

解法

type MyQueue struct {
    s1 []int
    s2 []int
}


func Constructor() MyQueue {
    m:=MyQueue{}
    m.s1=[]int{}
    m.s2=[]int{}
    return m
}


func (this *MyQueue) Push(x int)  {
    this.s1=append(this.s1,x)
}


func (this *MyQueue) Pop() int {
    value:=this.Peek()
    this.s2=this.s2[:len(this.s2)-1]
    return value
}


func (this *MyQueue) Peek() int {
    if len(this.s2)==0{
        for len(this.s1)>0{
            temp:=this.s1[len(this.s1)-1]
            this.s2=append(this.s2,temp)
            this.s1=this.s1[:len(this.s1)-1]
        }
    }
    return this.s2[len(this.s2)-1]
}


func (this *MyQueue) Empty() bool {
    if len(this.s1)==0 && len(this.s2)==0{
        return true
    }
    return false
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */

2.用队列实现栈

225. 用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false

注意:

你只能使用队列的基本操作 —— 也就是push to back、peek/pop from front、sizeis empty这些操作。 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例1

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

解法

type MyStack struct {
    queue1 []int
    queue2 []int
}


func Constructor() MyStack {
    m:=MyStack{}
    m.queue1=[]int{}
    m.queue2=[]int{}
    return m
}


func (this *MyStack) Push(x int)  {
    this.queue2=append(this.queue2,x)
    for len(this.queue1)>0 {
        this.queue2=append(this.queue2,this.queue1[0])
        this.queue1=this.queue1[1:]
    }
    this.queue1,this.queue2=this.queue2,this.queue1
}


func (this *MyStack) Pop() int {
  temp:=this.queue1[0]
  this.queue1=this.queue1[1:]
  return temp
}


func (this *MyStack) Top() int {
    return this.queue1[0]
}


func (this *MyStack) Empty() bool {
    if len(this.queue1)==0{
        return true
    }
    return false
}


/**
 * Your MyStack object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Top();
 * param_4 := obj.Empty();
 */

3.有效的括号

20. 有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。

示例1

输入: s = "()"
输出: true

示例2

输入: s = "()[]{}"
输出: true

示例3

输入: s = "(]"
输出: false

解法1

func isValid(s string) bool {
    statck:=[]byte{}
    for i:=0;i<len(s);i++{
        if s[i]=='(' || s[i]=='[' || s[i]=='{'{
            statck=append(statck,s[i])
        }else{
            if len(statck)==0{
                return false
            }else{
                temp:=statck[len(statck)-1]
                if s[i]==')' && temp=='('{
                    statck=statck[:len(statck)-1]
                    continue
                }else if s[i]==']' && temp=='['{
                    statck=statck[:len(statck)-1]
                    continue
                }else if s[i]=='}' && temp=='{'{
                    statck=statck[:len(statck)-1]
                    continue
                }else{
                    return false
                }
            }
        }
    }
    return len(statck)==0
}

解法2

func isValid(s string) bool {
    hashMap:=map[byte]byte{
        ')':'(',
        ']':'[',
        '}':'{',
    }
    stack:=[]byte{}
    for i:=0;i<len(s);i++{
        if s[i]=='(' || s[i]=='[' || s[i]=='{'{
            stack=append(stack,s[i])
        }else if len(stack)>0 && stack[len(stack)-1]==hashMap[s[i]]{
            stack=stack[:len(stack)-1]
        }else{
            return false
        }
    }
    return len(stack)==0
}

4.删除字符串中的所有相邻重复项

1047. 删除字符串中的所有相邻重复项

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

示例1

输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"

解法

func removeDuplicates(s string) string {
    stack:=[]byte{}
    for i:=0;i<len(s);i++{
        if len(stack)>0 && stack[len(stack)-1]==s[i]{
            stack=stack[:len(stack)-1]
        }else{
            stack=append(stack,s[i])
        }
    }
    return string(stack)
}

5.逆波兰表达式求值

150. 逆波兰表达式求值

根据逆波兰表示法,求表达式的值。

有效的算符包括+、-、*、/。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

注意 两个整数之间的除法只保留整数部分。

可以保证给定的逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

示例1

输入: tokens = ["2","1","+","3","*"]
输出: 9
解释: 该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9

示例2

输入: tokens = ["4","13","5","/","+"]
输出: 6
解释: 该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6

3

输入:tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
输出:22
解释:该算式转化为常见的中缀算术表达式为:
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

解法1

func evalRPN(tokens []string) int {
    stack:=[]string{}
    hashMap:=map[string]bool{
        "+":true,
        "-":true,
        "*":true,
        "/":true,
    }
    for i:=0;i<len(tokens);i++{
        if len(stack)>=2 && hashMap[tokens[i]] {
            nums1,_:=strconv.Atoi(stack[len(stack)-2])
            nums2,_:=strconv.Atoi(stack[len(stack)-1])
            var cur int
            if tokens[i]=="+"{
                cur=nums1+nums2
            }else if tokens[i]=="-"{
                cur=nums1-nums2
            }else if tokens[i]=="*"{
                cur=nums1*nums2
            }else{
                cur=nums1/nums2
            }
            stack=stack[:len(stack)-2]
            tmep:=strconv.Itoa(cur)
            stack=append(stack,tmep)
        }else{
            stack=append(stack,tokens[i])
        }
    }
    res,_:=strconv.Atoi(stack[0])
    return res
}

解法2

func evalRPN(tokens []string) int {
    stack:=[]int{}
    for i:=0;i<len(tokens);i++{
        val,err:=strconv.Atoi(tokens[i])
        if err==nil{
            stack=append(stack,val)
        }else{
            num1:=stack[len(stack)-2]
            num2:=stack[len(stack)-1]
            stack=stack[:len(stack)-2]
            switch tokens[i]{
            case "+":
                stack=append(stack,num1+num2)
            case "-":
                stack=append(stack,num1-num2)
            case "*":
                stack=append(stack,num1*num2)
            case "/":
                stack=append(stack,num1/num2)
            }
        }
    }
    return stack[0]
}

6.滑动窗口求最大值

239. 滑动窗口最大值

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回 滑动窗口中的最大值 。

示例1

输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置                最大值
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

示例2

输入: nums = [1], k = 1
输出: [1]

解法

func maxSlidingWindow(nums []int, k int) []int {
    m:=newQueueObj()
    res:=[]int{}
    for i:=0;i<k;i++{
        m.Push(nums[i])
    }
    res=append(res,m.Front())
    for i:=k;i<len(nums);i++{
        m.Pop(nums[i-k])
        m.Push(nums[i])
        res=append(res,m.Front())
    }
    return res
}

type newQueue struct{
    queue []int
}

func newQueueObj() *newQueue{
    m:=&newQueue{
        queue: []int{},
    }
    return m
}


func (this *newQueue) Front()int{
    return this.queue[0]
}

func (this *newQueue) Back()int{
    return this.queue[len(this.queue)-1]
}

func (this *newQueue)Push(val int){
    for len(this.queue)!=0 && val>this.Back(){
        this.queue=this.queue[:len(this.queue)-1]
    }
    this.queue=append(this.queue,val)
}

func (this *newQueue)Pop(val int){
    if len(this.queue)!=0 && val==this.Front(){
        this.queue=this.queue[1:]
    }
}

6.前k个高频元素

347. 前 K 个高频元素

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例1

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2

示例2

输入: nums = [1], k = 1
输出: [1]

解法

func topKFrequent(nums []int, k int) []int {
    hashMap:=make(map[int]int)
    for i:=0;i<len(nums);i++{
        hashMap[nums[i]]++
    }
    temp:=[]int{}
    for key,_:=range hashMap{
        temp=append(temp,key)
    }
    sort.Slice(temp,func(i,j int)bool{
        return hashMap[temp[i]]>hashMap[temp[j]]
    })
    return temp[:k]
}