1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| import java.util.ArrayList; import java.util.Arrays; import java.util.List;
public class K { public static void main(String[] args) { test(getList1());
System.out.println("-----");
test(getList2());
}
private static void test(List<Integer> list) { System.out.printf("第%s小的元素是%s%n", 3, getNumK(list, 3)); System.out.printf("第%s小的元素是%s%n", 2, getNumK(list, 2)); System.out.printf("第%s小的元素是%s%n", 1, getNumK(list, 1)); System.out.printf("第%s小的元素是%s%n", 5, getNumK(list, 5)); System.out.printf("第%s小的元素是%s%n", 8, getNumK(list, 8)); System.out.printf("第%s小的元素是%s%n", 9, getNumK(list, 9)); }
private static List<Integer> getList1() { return Arrays.asList(3, 7, 1, 2, 8, 9, 4, 5, 6); }
private static List<Integer> getList2() { return Arrays.asList(33, 7, 11, 22, 8, 99, 44, 55, 66); }
private static Integer getNumK(List<Integer> list, int k) { if (list.isEmpty()) { return null; }
if (list.size() < k) { return null; }
if (list.size() == 1 && k == 1) { return list.get(0); }
List<Integer> s1 = new ArrayList<>(); List<Integer> s2 = new ArrayList<>();
int p = list.get(0); for (int i = 1; i < list.size(); i++) { final Integer a = list.get(i); if (a < p) { s1.add(a); } else { s2.add(a); } }
if (k == s1.size() + 1) { return p; }
if (k < s1.size() + 1) { return getNumK(s1, k); } else { s1.add(p); return getNumK(s2, k - s1.size()); }
} }
|