商汤Java笔试
第一题:矩阵交集
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] split = line.split(" ");
int[] arr = new int[split.length];
for (int i = 0; i < split.length; i++) {
arr[i] = Integer.valueOf(split[i]);
}
Rectangle re1 = new Rectangle(arr[0], arr[1], arr[2], arr[3]);
Rectangle re2 = new Rectangle(arr[4], arr[5], arr[6], arr[7]);
Rectangle rec = re1.intersection(re2);
int X = rec.x;
int Y = rec.y;
int W = rec.width;
int H = rec.height;
if (X <= 0 || Y <= 0 || W <= 0 || H < 0) {
System.out.println("null");
} else {
System.out.println(X + " " + Y + " " + W + " " + H);
}
}
} 第二题:单词拆分 public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int index = str.indexOf(" ");
String str1 = str.substring(0, index);
String str2 = str.substring(index + 1);
String[] split = str2.split(",");
ArrayList<String> wordDict = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
wordDict.add(split[i]);
}
// 可以类比于背包问题
int n = str1.length();
// memo[i] 表示 s 中以 i - 1 结尾的字符串是否可被 wordDict 拆分
boolean[] memo = new boolean[n + 1];
memo[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (memo[j] && wordDict.contains(str1.substring(j, i))) {
memo[i] = true;
break;
}
}
}
System.out.println(memo[n]);
} 第三题:只能交易一次股票最高收益 public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String str1 = " ";
String[] split = str.split(str1);
int len = split.length;
int[] prices = new int[len];
for (int i = 0; i < len; i++) {
prices[i] = Integer.valueOf(split[i]);
}
if (len == 0) {
System.out.println(0);
}
int maxSum = 0;
int minpri = prices[0];
for (int i = 1; i < len; i++) {
if (prices[i] < minpri) {
minpri = prices[i];
} else {
int temp = prices[i] - minpri;
maxSum = Math.max(maxSum, temp);
}
}
System.out.println(maxSum);
}