1、输入一个数组[1, 0, -1, 2, -1];输出其中和为0的三元组,输出格式为[[1, 0, -1],[-1, 2, -1]]
这个题本身是不难的,但是笔试的平台什么也没给,和平时刷LeetCode不一样,需要自己写方法,自己写返回值,甚至main函数都要自己写,我在写的时候返回值设置成了List<int[]> 类型的,返回后无法输出为需要的格式。
package 面试;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/**
* @author : Lxd
* @date : 14:30 2021/6/19
*/
public class Main {
public static List<List<Integer>> add(int[] nums) {
Arrays.sort(nums);
int sum = 0;
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
sum = nums[i] + nums[start] + nums[end];
if (sum > 0) {
end--;
} else if (sum < 0) {
start++;
} else {
ArrayList<Integer> result = new ArrayList<>();
result.add(nums[i]);
result.add(nums[start]);
result.add(nums[end]);
if (!res.contains(result)) {
res.add(result);
}
start++;
end--;
}
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
s = s.substring(1,s.length()-1);
s = s.replaceAll(" ","");
String[] split = s.split(",");
int i = split.length;
int[] a = new int[i];
for (int j = 0; j < split.length; j++) {
a[j] = Integer.parseInt(split[j]);
}
List<List<Integer>>lists = add(a);
System.out.println(lists);
}
}
2、输入一个数,判断其是否为2的幂,输出true或者false
package 面试;
/**
* @author : Lxd
* @date : 15:00 2021/6/19
*/
public class TwoPower {
public static boolean isTwoPower(int a) {
int i = 1;
int flag = 1;
while (true) {
flag = flag << i;
if (flag > a) return false;
if (flag == a) return true;
}
}
public static void main(String[] args) {
System.out.println(isTwoPower(1024));
}
}
3、给俩个字符串,例如匹配值为pattern = “aabbc”,字符串为str = “cat cat dog dog pig”,则匹配,输出true,反之不匹配,输出false.
package 面试;
import java.util.HashMap;
import java.util.Map;
/**
* @author : Lxd
* @date : 15:12 2021/6/19
*/
public class Pattern_Str {
public static boolean isPattern(String pattern , String str){
String[] str1 = str.split(" ");
if (pattern.length() != str1.length) return false;
Map<Character,String> map = new HashMap<>();
for (int i = 0; i < str1.length; i++) {
if (!map.containsKey(pattern.charAt(i))){
if (!map.containsValue(str1[i])){
map.put(pattern.charAt(i),str1[i]);
} else {
return false;
}
}else {
if (!map.get(pattern.charAt(i)).equals(str1[i])){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
String pattern = "aabbcde";
String str = "cat cat dog dog c a s";
System.out.println(isPattern(pattern,str));
}
}
版权声明:本文为qq_45655489原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。