算法通关村第五关-白银挑战队列经典问题

大家好我是苏麟 , 今天带来几道经典小题 .

用栈实现队列

描述 :

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

实现 MyQueue 类:

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

题目 :

LeetCode 用栈实现队列

在这里插入图片描述

代码 :

class MyQueue {
    private Stack<Integer> sa;
    private Stack<Integer> sb;

    public MyQueue() {
        sa = new Stack<>();
         sb = new Stack<>();
    }
    
    public void push(int x) {
        sa.push(x);
    }
    
    public int pop() {
        int peek = peek();
        sb.pop();
        return peek;
    }
    
    public int peek() {
        if(!sb.isEmpty()){
            return sb.peek();
        }
        if(sa.isEmpty()){
            return -1;
        }
        while(!sa.isEmpty()){
            sb.push(sa.pop());
        }
        return sb.peek();
    }
    
    public boolean empty() {
        return sa.isEmpty() && sb.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

两数之和

相信大家对这道题还是很眼熟的 , 打开LeetCode第一道题就是它 , 对它可真的又爱又恨 , 很多新手朋友们想刷LeetCode但又不知道从哪开始就打开了第一题 , 结果就对算法失去了信心 .

这道题找对方法还是很容易的 , 下面我们就开始说说这道题 :

描述 ;

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

题目 :

LeetCode 1.两数之和 :

两数之和

在这里插入图片描述
分析 :

本题可以使用两层循环解决,第一层确定一个数,2,7,一直到11,然后内层循环继续遍历后序元素,判断是否存在target - x的数即可,代码如下:

class Solution {
    public int[] twoSum(int[] nums, int target) {
       
        for(int i= 0;i<nums.length ; i++){
            for(int j = i + 1;j<nums.length ; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i , j};
                }
            }
        }
        return new int[]{};
    }
}

这种方式的不足在于寻找 target -x 的时间复杂度过高,我们可以使用哈希表,可以将寻找 target -x的时间复杂度降低到从 O(N)降低到 O(1)。这样我们创建一个哈希表,对于每一个x,我们首先查询哈希表中是否存在 target - x,然后将 插入到哈希表中,即可保证不会让x 和自己匹配。

解析 :

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> hashMap = new HashMap<>();

        for(int i = 0; i < nums.length ; i++){
            if(hashMap.containsKey(target - nums[i])){
                return new int[] {hashMap.get(target - nums[i]),i};
            }
            hashMap.put(nums[i],i);
        }
        return new int[]{};
    }
}

这期就到这里 , 下一关见!

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值