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;
}