华为笔试0424
第一题
二分查找
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class H01 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> input = new ArrayList<>();
String line = in.nextLine();
String[] tokens = line.split(" "); // 使用正则表达式分割输入的字符串
for (String token : tokens) {
try {
int num = Integer.parseInt(token);
input.add(num);
} catch (NumberFormatException e) {
return;
}
}
int target = in.nextInt();
int[] nums = input.stream().mapToInt(Integer::valueOf).toArray();
String res = findTree(nums, target);
System.out.println(res);
}
public static String findTree(int[] nums, int target){
Arrays.sort(nums);
int left = 0, right = nums.length - 1;
StringBuilder res = new StringBuilder("S");
while (left < right){
int mid = (left + right) / 2;
if(nums[mid] == target){
res.append("Y");
return res.toString();
} else if (nums[mid] > target) {
right = mid - 1;
res.append("L");
}
else {
left = mid + 1;
res.append("R");
}
}
if(left == right && nums[left] == target){
res.append("Y");
}
else {
res.append("N");
}
return res.toString();
}
}
第二题
排序
import java.util.*;
public class H02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
List<Player> players = new ArrayList<>();
for (int i = 1; i <= n; i++) {
String shots = sc.next();
int goals = 0;
int maxConsecutive = 0;
int currentConsecutive = 0;
int firstMiss = 0;
for (int j = 0; j < m; j++) {
if (shots.charAt(j) == '1') {
goals++;
currentConsecutive++;
maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
} else {
currentConsecutive = 0;
firstMiss = j;
}
}
players.add(new Player(i, goals, maxConsecutive, firstMiss));
}
players.sort((a, b) -> {
if (a.goals != b.goals) {
return b.goals - a.goals;
}
if (a.maxConsecutive != b.maxConsecutive) {
return b.maxConsecutive - a.maxConsecutive;
}
if(a.firstMiss != b.firstMiss){
return b.firstMiss - a.firstMiss;
}
return a.id - b.id;
});
int len = players.size();
for(int i = 0; i < len - 1; i++){
System.out.print(players.get(i).id + " ");
}
System.out.println(players.get(len - 1).id);
}
}
class Player {
int id;
int goals;
int maxConsecutive;
int firstMiss;
Player(int id, int goals, int maxConsecutive, int firstMiss) {
this.id = id;
this.goals = goals;
this.maxConsecutive = maxConsecutive;
this.firstMiss = firstMiss;
}
}