package org.example.interview.practice; import java.util.Comparator; import java.util.PriorityQueue; /** * @author xianzhe.ma * @date 2021/8/22 */ public class NC_85_MIN_STRING { public String minString (String[] strs) { // write code here if(strs == null || strs.length < 1) { return null; } // 重载比较函数 PriorityQueue<String> queue = new PriorityQueue<>(new Comparator<String>() { public int compare(String s1, String s2) { // 保证 s1 + s2 > s2 + s1 时,返回值大于0,否则返回值小于0 // 保证queue中越靠近队头的元素,字典序越小 return (s1 + s2).compareTo(s2 + s1); } }); // 放入队列中排好序 for(String str : strs) { queue.offer(str); } StringBuilder res = new StringBuilder(); // 重新从队列中获取 while(queue.size() > 0) { res.append(queue.poll()); } return res.toString(); } }
package org.example.interview.practice; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; /** * @author xianzhe.ma * @date 2021/7/9 * 注意是找第K大的数,而不是排序过后按照从小到大的第k-1下标比如 10,10,9,9,8 如果K=3,返回是9 因为第一第二大是10,10 第三大就是9 * 如果是查找按照从小到大顺序的第K个数,那就用大顶堆 */ public class NC_88_KTH { // public static int findKth(int[] a, int n, int K) { // // write code here // PriorityQueue<Integer> queue = new PriorityQueue<>( new Comparator<Integer>() { // // @Override // public int compare(Integer o1, Integer o2) { // // return o2-o1; // } // }); // for (int i=0;i<K;i++) { // queue.offer(a[i]); // } // // for (int j=K;j<n;j++) { // Integer value = queue.peek(); // if (a[j]<value) { // queue.poll(); // queue.offer(a[j]); // } // } // // return queue.poll(); // } public static int findKth(int[] a, int n, int K) { // write code here //小根堆 PriorityQueue<Integer> pq = new PriorityQueue<>() ; for (int i=0;i<K;i++) { pq.add(a[i]) ; } for(int i = K ; i < n ; i++) { if(a[i] > pq.peek()){ pq.poll() ; pq.add(a[i]) ; } } return pq.peek() ; } public static void main (String[] args) { int[] arr = {5,7,4,2,10,8,22,44,1}; // int[] arr = {1332802,1177178,1514891,871248,753214,123866,1615405,328656,1540395,968891,1884022,252932,1034406,1455178,821713,486232,860175,1896237,852300,566715,1285209,1845742,883142,259266,520911,1844960,218188,1528217,332380,261485,1111670,16920,1249664,1199799,1959818,1546744,1904944,51047,1176397,190970,48715,349690,673887,1648782,1010556,1165786,937247,986578,798663}; Arrays.sort(arr); System.out.println(arr[3]); int value = findKth(arr, arr.length, 4); System.out.println(value); } }
import java.util.*; public class NC_86_FIND_ELEMENT{ public int[] findElement(int[][] mat, int n, int m, int x) { // write code here int[] result = new int[2]; int row = 0; int col = m - 1; while(row < n && col >= 0) { if(mat[row][col] == x) { result[0] = row; result[1] = col; break; } if(x > mat[row][col]) { row ++; } else { col --; } } return result; } }