软件开发架构师

TopK

java 70 2019-02-25 15:17

网易面试挂了,伤心。

一面面试官不是搞技术的,二面面试官搞ios,全程不问JVM,并发的知识,运气真差

而且手撸代码硬伤,没得编译

准备先在IDE敲一遍,在再纸上面写一遍。

 1 package com.qiuzhao.test;
 2 
 3 import java.util.PriorityQueue;
 4 import java.util.Queue;
 5 
 6 /**
 7  * @Auther: Chang
 8  * @Date: 2018/8/27
 9  */
10 public class topK {
11     public static void main(String[] args) {
12 
13         int[] a = {489, 500, 111, 100, 2, 7, 3, 8, 66, 888};
14         int k = 3;
15         // 第一种 推排序
16         prioritySort(a, k);
17         // 第二种 快速排序
18         quickSort(a, k);
19     }
20 
21     // 堆排序 int[] a = {489, -5, 111, 100, 2, 7, 3, 8, 66, 88};
22     private static void prioritySort(int[] a, int k) {
23         Queue<Integer> pq = new PriorityQueue<>(k);
24         for (int i = 0; i < a.length; i++) {
25             int n = pq.size();
26             if (n >= k && a[i] > pq.peek()) {
27                 pq.poll();
28             }
29             n = pq.size();
30             if (n < k) pq.add(a[i]);
31         }
32         pq.forEach(x -> System.out.print(x + "  "));
33         System.out.println();
34     }
35 
36     private static void quickSort(int[] a, int k) {
37 
38         int left = 0;
39         int right = a.length - 1;
40         int mid = partition(a, left, right);
41         while (mid != k) {
42             if (mid > k) {
43                 right = mid - 1;
44                 mid = partition(a, left, right);
45             } else {
46                 left = mid + 1;
47                 mid = partition(a, left, right);
48             }
49         }
50         for (int i = 0; i < mid; i++) {
51             System.out.print(a[i] + "  ");
52         }
53         System.out.println();
54     }
55 
56     private static int partition(int[] a, int left, int right) {
57 
58         int temp = a[left];
59         while (left < right) {
60             while (left < right && a[right] <= temp) right--;
61             a[left] = a[right];
62             while (left < right && a[left] >= temp) left++;
63             a[right] = a[left];
64         }
65         a[left] = temp;
66         return left;
67     }
68 }

 

文章评论