JAVA刷题(4)

wangzihaogg wangzihaogg 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

使用队列拦截数据

有一个 int 数组,包含 n 个数且有序,分别是 1、2、···、n,它们被队列 Queue 拦截(进入队列,数据也可能不进入队列)后得到一串序列。现在给你一串 1 ~ n 的序列,请你判断该序列是否是被队列 Queue 拦截后得到的序列,并通过 isOutByQueue 函数返回结果。 例:

  • 序列:[2, 3, 1, 4]

  • 根据序列可以知道数据个数为 n = 4,有序数组为:[1, 2, 3, 4]

  • 该序列可以通过以下方法得到:

    • 有序数组经过队列 Queue 时,1 被队列拦截住(进入队列),2 和 3 未被拦截,得到序列:[2, 3],队列中数据:[1];

    • 接着 1 在数字 4 进入序列前,离开队列 Queue 进入序列,得到:[2, 3, 1];

    • 最后数字 4 进入序列,得到:[2, 3, 1, 4]

可以得到,序列:[2, 3, 1, 4] 是被队列 Queue 拦截后得到的序列

import java.util.*;
​
public class Solution {
    public boolean isOutByQueue(int[] nums) {
        Queue<Integer> q = new LinkedList<>();
        int pre_max = 0;
​
        for(int elem:nums){
            if(elem>pre_max){
                for(int i=pre_max+1;i<elem;i++){
                    q.add(i);
                }
                pre_max = elem;
            }else if(q.isEmpty() || elem!=q.peek()){
                return false;
            }else{
                q.poll();
            }
        }
        return true;
    }
​
}
import java.lang.reflect.*;
import java.util.*;
​
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
​
        String in = sc.nextLine();
        String[] str = in.replace("[", "").replace("]", "").trim().split(",");
        int[] nums = new int[str.length];
        for (int i = 0; i < str.length; i++) {
            try {
                nums[i] = Integer.parseInt(str[i].trim());
            } catch (Exception e) {
                nums[i] = 0;
            }
        }
        Solution solution = new Solution();
        System.out.println(solution.isOutByQueue(nums));
​
        sc.close();
    }
}
...全文
评论
收藏 已收藏
分享
返回顶部