1、寻找第K大。
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
public static int findKth(int[] a, int n, int K) {
return findKth2(a, 0,n-1, K);
}
private static int findKth2(int[] a, int left, int right, int k) {
int index = partition(a, left, right);
if (index - left + 1 == k) {
return a[index];
} else if (index - left + 1 > k) {
return findKth2(a,left,index-1, k);
} else {
return findKth2(a, index + 1, right, k-index+left-1);
}
}
private static int partition(int[] a, int left, int right) {
int baseValue = a[left], i = left, j = right;
while (i < j) {
while (i < j && a[j] <= baseValue) {
j--;
}
a[left] = a[right];
while (j > i && a[i] >= baseValue) {
i++;
}
a[right] = a[left];
}
a[left] = baseValue;
return left;
}
思路:1、进行一次快排,大的元素放在后面,小的元素放在前面,得到中间轴为index。
2、如果index-left+1==k,输出a[index].
3、如果index-left+1 > k,则目标元素在前半段,更新right = index-1。继续第一步。
4、如果index-left+1 < k,则目标元素在后半段,更新left = index + 1, k = k - index + left - 1。继续第一步。
2、找出字符串中连续最长的数字串
import java.util.Scanner;
public class solution3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String s1 = scanner.nextLine();
int count = 0, end = 0, max = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) >= '0' && s1.charAt(i) <= '9') {
count++;
if (count > max) {
max = count;
end = i;
}
}else {
count = 0;
}
}
System.out.println(s1.substring(end - max + 1, end + 1));
}
}
}
思路:max表示经过的速度最大值,count是数字计数器。如果为字母时count置为0
end是数字尾部,每次满足数字时,count++,与max进行比较,max小于count时,更新max和end。
3、删除公共字符串
import java.util.Scanner;
public class solution4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.nextLine();
String s2 = scanner.nextLine();
char[] ch = s1.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (!s2.contains(String.valueOf(ch[i]))) {
System.out.print(ch[i]);
}
}
}
}
4、神奇的口袋
有一个神奇的口袋,总的容积是40,用这个口袋可以变出一些物品,这些物品的总体积必须是40。John现在有n个想要得到的物品,每个物品的体积分别是a1,a2……an。John可以从这些物品中选择一些,如果选出的物体的总体积是40,那么利用这个神奇的口袋,John就可以得到这些物品。现在的问题是,John有多少种不同的选择物品的方式。
import java.util.Scanner;
public class solution5 {
static int weight[];
static int count;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = 0;
while (scanner.hasNext()) {
n = scanner.nextInt();
weight = new int[n+1];
for (int i = 1; i < n + 1; i++) {
weight[i] = scanner.nextInt();
}
count(40,n);
System.out.println(count);
}
}
private static void count(int s, int n) {
if (s==0) {
count++;
return;
}
if (s<0 || s>0&&n<0) {
return;
}
count(s-weight[n],n-1);
count(s,n-1);
}
}
思路:1、n个物品依次放入weight中。
2、递归函数count(int s, int n) s 为剩余重量,n为可选的物品个数。
3、从后往前往包内装物品,先装入第n个物品,若此时剩余物品仍然有解。则count(s-weight[n], n-1).
4、装了weight[n]后,无解,从count(s,n-1)开始。