第一题
1,5,10,50,100五种纸币,每种对应一个数量,求找零所需最小纸币数,如无方案输出-1。
思路:贪心算法,从100币值依次往下找即可
第二题
给一个数列和按某种排序方式每一步生成的数列,要求实现该排序算法并输出每一步内容。 很明显是快排,通过率100%。
import java.util.Scanner;
public class QuickSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
quicksort(nums, 0, n - 1);
}
public static void quicksort(int[] nums, int left, int right) {
if (left >= right) {
return;
}
int mid = partition(nums, left, right);
print(nums);
quicksort(nums, left, mid - 1);
quicksort(nums, mid + 1, right);
}
public static void print(int[] nums) {
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]);
if (i != nums.length - 1) {
System.out.print(" ");
}
}
System.out.println();
}
public static int partition(int[] nums, int left, int right) {
if (left >= right) {
return left;
}
int i = left;
int j = right;
int key = nums[left];
while (i < j) {
while (i < j && nums[j] >= key) {
j--;
}
while(i < j && nums[i] <= key) {
i++;
}
if(i < j){
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
nums[left] = nums[i];
nums[i] = key;
return i;
}
}
第三题
(0,0)(4,2)代表矩形两个对角顶点。输入8个数字代表两个矩形,求二者是否相交,相交返回1,反之返回0
import java.util.Scanner;
public class Square {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] square1 = new int[2][2], square2 = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
square1[i][j] = sc.nextInt();
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
square2[i][j] = sc.nextInt();
}
}
if (xIn(square1, square2) && yIn(square1, square2)) {
System.out.print(1);
} else {
System.out.print(0);
}
}
public static boolean xIn(int[][] square1, int[][] square2) {
return square2[0][0] >= square1[0][0] && square2[0][0] <= square1[1][0];
}
public static boolean yIn(int[][] square1, int[][] square2) {
return square2[0][1] >= square1[0][1] && square2[0][0] <= square1[1][1];
}
}
第四题
从输入的字符串中提取整数,如+1a2返回12,要求尽可能多包含异常处理。
import java.util.Scanner;
public class GetNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
long res= 0;
boolean flag = true;
int is_positive = 1;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isDigit(c)) {
flag = false; //出现数字,则不再接收任何符号
res*= 10;
res+= c - '0';
}
if (flag && c == '+') {
flag = false; //不再接收任何符号
continue;
}
if (flag && c == '-') {
is_positive = -1; //表示为负数
flag = false; //不再接收任何符号
continue;
}
}
System.out.print(res* is_positive);
}
public static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
}