每日刷题【day019】

1、数组中的第K个最大元素

在这里插入图片描述

public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> queue=new PriorityQueue<>(Collections.reverseOrder());
    for (int num : nums) {
        queue.add(num);
    }
    for (int i = 0; i < k; i++) {
        if (i==k-1) return queue.peek();
        queue.poll();
    }
    return -1;
}

2、前K个高频单词

在这里插入图片描述

public List<String> topKFrequent(String[] words, int k) {
   Map<String,Integer> map=new HashMap<>();
    List<String> res=new ArrayList<>();
    for (String word : words) {
        if (map.containsKey(word)) map.put(word,map.get(word)+1);
        else map.put(word,1);
    }
    PriorityQueue<String> queue=new PriorityQueue<>(((o1, o2) -> {
        int v1=map.get(o1);
        int v2=map.get(o2);
        if (v1!=v2) return v2-v1;
        return o1.compareTo(o2);
    }));
    queue.addAll(map.keySet());
    for (int i=0;i<k;i++){
        res.add(queue.poll());
    }
    return res;
}

3、环形链表

判断是否环形链表

public boolean hasCycle(ListNode head) {
    if (head==null||head.next==null) return false;
    ListNode s=head;
    ListNode f=head.next;
    while (f!=s){
        if (f==null||f.next==null) return false;
        s=s.next;
        f=f.next.next;
    }
    return true;
}

4、转置矩阵

在这里插入图片描述

public int[][] transpose(int[][] matrix) {
    int[][] res=new int[matrix[0].length][matrix.length];
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            res[j][i]=matrix[i][j];
        }
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值