题目描述
给定一个整型数组arr,找到其中最小的k个数。
import java.util.*;
public class Main {
public static void main(String[] args) {
//输入数据
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int[] array = new int[m];
int n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < m; i++) {
array[i] = sc.nextInt();
}
//函数调用
int[] result = test(array, n);
//显示结果
for (int V : result) {
System.out.println(V);
}
}
private static int[] test(int[] array, int n) {
int[] result = new int[n];
Arrays.sort(array);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
}
给定一个无序单链表,实现单链表的选择排序(按升序排序)。
import java.util.*;
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class Main {
public static void main(String[] args) {
ListNode root = test();
while (root != null) {
System.out.print(root.val+" ");
root = root.next;
}
}
public static ListNode test() {
//数据的输入
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
sc.nextLine();
ArrayList list = new ArrayList();
for (int i = 0; i < m; i++) {
list.add(sc.nextInt());
}
//函数的调用
Collections.sort(list);
ListNode root = new ListNode(0);
ListNode cur = root;
for (int V : list) {
cur.next = new ListNode(V);
cur = cur.next;
}
return root.next;
}
}
给定两个有序数组arr1和arr2,再给定一个整数k,返回来自arr1和arr2的两个数相加和最大的前k个,两个数必须分别来自两个数组按照降序输出
[要求]:时间复杂度为O(klogk)O(k \log k)O(klogk)