昨天做了美团的笔试,现在复盘一下。
1、将数组按照绝对值大小排序
有道算法题解决思路需要将数组按照绝对值大小进行排序,我使用的是sort方法+Comparator比较器实现的,这里记录一下:
public static void main(String[] args) {
Integer nums[] = new Integer[10];
nums[0] = -3;
nums[1] = 5;
nums[2] = 4;
nums[3] =1;
nums[4] = -2;
nums[5] = -5;
nums[6] = -4;
nums[7] =-1;
nums[8] = 3;
nums[9] = 2;
System.out.println(Arrays.toString(nums));//排序前
Arrays.sort(nums,new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return Math.abs(o1)-Math.abs(o2);
}
});
System.out.println(Arrays.toString(nums));//排序后
}
运行结果:
2、String的matches()方法
有一道算法题需要判断字符串里出现的字符,需要用到matches()方法,这里补一下用法。
public static void main(String[] args) {
//匹配字符
String regex = "a....s"; //若不限制a和s之间字符的数量,可以写为:String regex = "a.*s";
System.out.println("abbbbs".matches(regex)); // true
System.out.println("alias".matches(regex)); // false
System.out.println("as".matches(regex)); // false
//匹配数字
String regex1 = "[24680]+"; //表示匹配一个或多个数字字符,而[24680]表示只匹配一个数字字符。
System.out.println("abc".matches(regex1)); // false
System.out.println("846".matches(regex1)); // true
System.out.println("98 4".matches(regex1)); // false,不允许空字符
}