刷算法题常用工具类集锦(Java)

53 阅读5分钟

iPad壁纸🗓文字篇19_9_舞木子_来自小红书网页版.jpg

前言

本文章用于记录解算法题中常被用到的一些类及相关方法,在很多平台解算法题是没有智能补全或提示的,所以只能靠记,记住这些工具类及其用法是解题的基础。

队列

Queue

// `ArrayDeque` 是 Java 中实现 `Deque` 接口的一个类,它可以用作队列(FIFO)或双端队列(LIFO)。
Queue<Integer> queue=new ArrayDeque<>();
// 常用方法
// 1. 元素入队
queue.add(10); // 添加元素到队列尾部 如果队列已满,抛出 `IllegalStateException`
queue.offer(20); // 添加元素到队列尾部,如果队列已满,返回 `false`,而不是抛出异常。

// 2. 元素出队
int firstElement = queue.remove(); // 移除并返回队列头部的元素,如果队列为空,抛出 `NoSuchElementException`。
Integer firstElementOrNull = queue.poll(); // 移除并返回队列头部的元素,队列为空时返回 null

// 3. 查看队头元素
int headElement = queue.element(); // 返回队列头部的元素,但不移除,如果队列为空,抛出 `NoSuchElementException`。
Integer headElementOrNull = queue.peek(); // 返回队列头部的元素,队列为空时返回 null

// 4. 其他常用方法
int size = queue.size(); // 返回队列中的元素数量
boolean isEmpty = queue.isEmpty(); // 检查队列是否为空
queue.clear(); // 清空队列

// 5. 双端队列操作
// 虽然 `ArrayDeque` 可以用作队列,但它也支持双端队列的操作
queue.addFirst(5); // 将元素添加到队列头部
queue.addLast(15); // 将元素添加到队列尾部
int first = queue.removeFirst(); // 移除并返回队列头部的元素
int last = queue.removeLast(); // 移除并返回队列尾部的元素
int head = queue.getFirst(); // 返回队列头部的元素
int tail = queue.getLast(); // 返回队列尾部的元素

优先队列

PriorityQueue 是 Java 中基于优先级堆(Priority Heap)实现的一个队列,它的元素按照优先级顺序出队(默认是最小堆,即最小元素优先出队)。以下是 PriorityQueue 的使用示例,其有的方法和普通队列一样,只是会根据排序规则决定出队的顺序而已。

    // 匿名实现比较器
    public static Comparator<Customer> idComparator = new Comparator<Customer>() {
        @Override
        public int compare(Customer c1, Customer c2) {
            return c1.getId() - c2.getId(); // 按 ID 升序排列
        }
    };
    
    // 创建优先队列,指定初始容量和比较器
    Queue<Customer> customerPriorityQueue = new PriorityQueue<>(7, idComparator);
    
    /*
        更简洁的写法: 使用 Lambda 表达式实现比较器
        Queue<Customer> customerPriorityQueue = new PriorityQueue<>(7, (c1, c2) -> c1.getId() - c2.getId());
    */
    
    // 添加元素
    customerPriorityQueue.add(new Customer(5));
    customerPriorityQueue.add(new Customer(1));
    customerPriorityQueue.add(new Customer(3));

PriorityQueue 不是线程安全的。如果需要在多线程环境中使用,可以使用 java.util.concurrent.PriorityBlockingQueue

Deque

// 可用以下这 3 种实现
Deque<Integer> stack = new ArrayDeque<>();

Deque<Integer> stack=new LinkedList<>(); 

Stack<Integer> stack=new Stack<>();

/*
    常用方法
-   `void push(E e)`: 将元素压入栈顶。
-   `E pop()`: 移除并返回栈顶元素。
-   `E peek()`: 返回栈顶元素,但不移除。
-   `boolean isEmpty()`: 检查栈是否为空。
-   `int size()`: 返回栈中元素的数量。
-   `void clear()`: 清空栈。
*/

三者区别:

特性ArrayDequeStackLinkedList
底层数据结构动态循环数组动态数组(继承自 Vector双向链表
线程安全不安全安全(同步机制)不安全
性能高效(O(1) 操作)较低(同步开销)高效(O(1) 操作)
推荐使用场景栈或双端队列不推荐使用(设计较老)栈或双端队列
随机访问不支持支持不支持
额外功能双端队列操作search() 方法双端队列操作

数组

Arrays

// 整数数组求和
int total= Arrays.stream(nums).sum();
// 整数数组获取最小值
int min = Arrays.stream(nums).min().getAsInt();

// 排序
Arrays.sort(nums);

// 数组比较
Arrays.equals(nums1, nums2);

字符

// 判断字符是否是 字母 或 数字
Character.isLetterOrDigit(ch1);
// 将字符转为小写(对字母而言)
Character.toLowerCase(ch1);  // 用于将字符转换为小写。如果字符已经是小写或不是字母,则返回原字符

字符串

字符串数组拼接

String.join(" ",strs);

字符串构建

StringBuffer cur = new StringBuffer();
cur.append(str);
cur.delete(start, cur.length());

字符串转字符数组

char[] sc = str.toCharArray();

随机数生成

// 1. 使用 Random 生成随机数
Random random = new Random();
// 生成一个 0 到 9 之间的随机整数
int a = random.nextInt(10);
// 生成一个 0 到 9 之间的随机 long 整数
long b = random.nextLong(10);
// 生成一个 0 到 10(不包含) 之间的随机浮点数
double c = random.nextDouble(10);

// 2. 使用 Math.random() 生成随机数
// `Math.random()` 是 `Math` 类的静态方法,返回一个 `[0.0, 1.0)` 范围内的伪随机 `double` 值。
// 通过乘以一个范围值并强制转换为 `int`,可以生成一个随机整数
int num = (int) (Math.random() * 10); // 生成一个 0 到 9 的随机整数

两种方法对比

特性Random.nextInt(int bound)Math.random() + 强制转换
Random 类Math 类
方法nextInt(int bound)Math.random()
返回值[0, bound) 范围内的 int[0.0, 1.0) 范围内的 double
随机性伪随机数,基于种子伪随机数,基于系统时间
性能较高较低(涉及浮点数运算和转换)
线程安全不安全安全(静态方法)
适用场景需要生成多个随机数时生成单个随机数或简单场景

集合

元素排序

        // 使用匿名内部类实现比较器,按值降序排列
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue()); // 降序排列
            }
        });
        
        // 使用 Lambda 表达式简化代码
        Collections.sort(list, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
        
        // 对于简单的比较规则,可以使用 `Comparator.comparing` 方法。例如:Comparator.comparingInt(Customer::getId)
        Collections.sort(list, Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder()));

元素删除

//此处需要注意list.remove()方法中的参数传的是索引
list.remove(list.size()-1);
// 传的是key
hashMap.remove(val);

元素交换

// 集合元素交换
Collections.swap(curList, i, first);

基本类型

// 字符串转整型
Integer a = Integer.parseInt(s);

内容会继续更新、完善 ~