Leetcode Java常用代码

自定义排序

class Compare implements Comparator<int[]> {
    @Override
    public int compare(int[] a, int[] b){
        if(a[0] > b[0]){
            return 1;
        }else if (a[0] == b[0]){
            if (a[1] == b[1]){
                return 0;
            }else if(a[1] > b[1]){
                return 1;
            }
            return -1;
        }else{
            return -1;
        }
    }
}

Collections.sort(a, new Compare());

优先队列

class Solution {
    class Compare implements Comparator<int[]> {
        @Override
        public int compare(int[] a, int[] b){
            return -1 * Integer.compare(a[0], b[0]);
        }
    }
    public int[] topKFrequent(int[] nums, int k) {
        PriorityQueue<int[]> p = new PriorityQueue<>(new Compare());
        Map<Integer, Integer> c = new HashMap<>();
        for(int num: nums){
            c.put(num, c.getOrDefault(num, 0) + 1);
        }
        for(Integer num: c.keySet()) {
            p.add(new int[] {c.get(num), num});
        }
        int[] result = new int[k];
        for(int i=0; i<k; i++){
            result[i] = p.poll()[1];
        }
        return result;
    }
}

Map常用方法

m.put(num, m.getOrDefault(num, 0) + 1);
d.computeIfAbsent(content, k -> new LinkedList<>()).add(p + "/" + name);

字符串常用方法

String[] t = tmp[i].split("\\(");
String content = t[1].substring(0, t[1].length() - 1);

int a = 10;
String b = String.valueOf(a);
Integer c = 20;
String d = c.toString();
String e = "" + a;

String a = "10";
Integer b = Integer.parseInt(a);

Array与List

// 深拷贝
int[] originalArray = {1, 2, 3, 4, 5};
int[] deepCopyArray1 = Arrays.copyOf(originalArray, originalArray.length);

List<Integer> originalList = new ArrayList<>();
List<Integer> deepCopyList1 = new ArrayList<>(originalList);

// Array与List相互转换
Integer[] a = new Integer[] {1,2,3};
List<Integer>b = new LinkedList<>(Arrays.asList(a));

Integer[] c = new Integer[b.size()];
b.toArray(c);

Related post

  1. 异常处理的合理使用与防御式编程

    2022-02-21

  2. MapReduce代码编写总览

    2021-09-20

  3. Java IO流

    2020-07-31

  4. 基于vue的微信小程序开发

    2020-07-30

There are no comment yet.

COMMENT

Take a Coffee Break

Recommend post

  1. 常用工具指令

    2022-09-18

Category list

ABOUT

Welcome to FullStar, a captivating online destination where the realms of software development and personal reflections intertwine.

April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Life Logs

  1. 回首

    2023-07-14

Return Top