当前位置:   article > 正文

华为机考-java牛客网/力扣 部分刷题记录_输入处理(重要):hj5.进制转换

输入处理(重要):hj5.进制转换

【刷题题型】

1. 入门题(5题)

(1) 输入处理(重要):HJ5.进制转换

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. String s = in.nextLine();
  6. if(s.contains("0x")){
  7. s = s.substring(2);
  8. }
  9. Integer n = Integer.parseInt(s,16);
  10. System.out.println(n.toString());
  11. }
  12. }
  13. /*
  14. 16转10
  15. Integer.parseInt(string,16);
  16. 10转2
  17. Integer.toBinaryString(num);
  18. 10转8
  19. Integer.toOctalString(num);
  20. 10转16
  21. Integer.toHexString(num);
  22. */
  23. public static void main(String[] args){
  24. Scanner in = new Scanner(System.in);
  25. String s = in.next();
  26. System.out.println(Integer.parseInt(s.substring(2),16));
  27. }

(2) 排列组合:(牛客搜索)NC61.两数之和

  1. import java.util.*;
  2. public class Solution {
  3. /**
  4. *
  5. * @param numbers int整型一维数组
  6. * @param target int整型
  7. * @return int整型一维数组
  8. */
  9. public int[] twoSum (int[] numbers, int target) {
  10. // write code here
  11. Map<Integer,Integer> map = new HashMap();
  12. int[] num = new int[2];
  13. for(int i = 0; i < numbers.length; i++){
  14. Integer sum = target - numbers[i];
  15. if(map.containsKey(sum)){
  16. num[0] = map.get(sum);
  17. num[1] = i+1;
  18. break;
  19. } else {
  20. map.put(numbers[i],i+1);
  21. }
  22. }
  23. return num;
  24. }
  25. }

(3) 快速排序:HJ3.明明的随机数 Arrays.sort();

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. int n = in.nextInt();
  6. int[] m= new int[n];
  7. for(int i = 0; i < n; i++){
  8. m[i] = in.nextInt();
  9. }
  10. in.close();
  11. Arrays.sort(m);
  12. System.out.println(m[0]);
  13. for(int i = 1; i < n; i++){
  14. if(m[i] != m[i-1]){
  15. System.out.println(m[i]);
  16. }
  17. }
  18. }
  19. }

(4) 哈希表:HJ10.字符个数统计

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. String s = in.next();
  6. Set<String> set = new HashSet();
  7. for(int i = 0; i < s.length(); i++){
  8. String str = s.substring(i,i+1);
  9. set.add(str);
  10. }
  11. System.out.println(set.size());
  12. }
  13. }

(5) 递归:NC68.跳台阶

  1. public class Solution {
  2. public int jumpFloor(int target) {
  3. if(target == 1 || target == 0){
  4. return 1;
  5. }
  6. if(target == 2){
  7. return 2;
  8. }
  9. return jumpFloor(target - 1) + jumpFloor(target - 2);
  10. }
  11. }
  12. import java.util.*;
  13. public class Solution {
  14. Map<Integer,Integer> map = new HashMap();
  15. public int jumpFloor(int target) {
  16. if(target == 1 || target == 0){
  17. return 1;
  18. }
  19. if(target == 2){
  20. return 2;
  21. }
  22. if(map.containsKey(target)){
  23. return map.get(target);
  24. } else{
  25. map.put(target,jumpFloor(target - 1) + jumpFloor(target - 2));
  26. return map.get(target);
  27. }
  28. }
  29. }

2.字符串操作(6题)(带*题目与第一第二道题目难度相近,以下题目基本覆盖大部分知识点)

(1) HJ17.坐标移动

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args) {
  4. Scanner in = new Scanner(System.in);
  5. String s = in.nextLine();
  6. in.close();
  7. String[] str = s.split(";");
  8. int[] n = new int[2];
  9. java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[0-9]*");
  10. for(String s1 : str){
  11. if(s1.length() <= 3 && s1.length() >= 2 && pattern.matcher(s1.substring(1)).matches()){
  12. String s2 = s1.substring(0,1);
  13. Integer s4 = Integer.parseInt(s1.substring(1));
  14. if("A".equals(s2)){
  15. n[0] = n[0] - s4;
  16. }else if("D".equals(s2)){
  17. n[0] = n[0] + s4;
  18. }else if("W".equals(s2)){
  19. n[1] = n[1] + s4;
  20. }else if("S".equals(s2)){
  21. n[1] = n[1] - s4;
  22. }
  23. }
  24. }
  25. System.out.println(n[0]+","+n[1]);
  26. }
  27. }

正则表达式:

(2) HJ20.密码验证合格程序

  1. import java.util.*;
  2. import java.util.regex.*;
  3. public class Main{
  4. public static void main(String[] args){
  5. Scanner in = new Scanner(System.in);
  6. while(in.hasNext()){
  7. String s = in.next();
  8. if(s.length() <= 8){
  9. System.out.println("NG");
  10. continue;
  11. }
  12. if(getMatch(s)){
  13. System.out.println("NG");
  14. continue;
  15. }
  16. if(getString(s,0,3)){
  17. System.out.println("NG");
  18. continue;
  19. }
  20. System.out.println("OK");
  21. }
  22. }
  23. private static boolean getString(String str,int l,int r){
  24. if(r >= str.length()){
  25. return false;
  26. }
  27. if(str.substring(r).contains(str.substring(l,r))){
  28. return true;
  29. } else {
  30. return getString(str,l+1,r+1);
  31. }
  32. }
  33. private static boolean getMatch(String str){
  34. int count = 0;
  35. Pattern p1 = Pattern.compile("[A-Z]");
  36. if(p1.matcher(str).find()){
  37. count++;
  38. }
  39. Pattern p2 = Pattern.compile("[a-z]");
  40. if(p2.matcher(str).find()){
  41. count++;
  42. }
  43. Pattern p3 = Pattern.compile("[0-9]");
  44. if(p3.matcher(str).find()){
  45. count++;
  46. }
  47. Pattern p4 = Pattern.compile("[^a-zA-Z0-9]");
  48. if(p4.matcher(str).find()){
  49. count++;
  50. }
  51. if(count >= 3){
  52. return false;
  53. }
  54. return true;
  55. }
  56. }

(3) *HJ23.删除字符串中出现次数最少的字符

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. String s = in.next();
  6. in.close();
  7. Map<Character,Integer> map = new HashMap();
  8. StringBuffer str = new StringBuffer();
  9. for(char c : s.toCharArray()){
  10. map.put(c,map.getOrDefault(c,1)+1);
  11. }
  12. int min = Integer.MAX_VALUE;
  13. for(int e : map.values()){
  14. min = Math.min(min,e);
  15. }
  16. for(char c : s.toCharArray()){
  17. if(map.get(c) != min){
  18. str.append(c);
  19. }
  20. }
  21. System.out.println(str);
  22. }
  23. }

(4) *HJ33.整数与IP地址间的转换

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. while(in.hasNext()){
  6. String s = in.next();
  7. if(s.contains(".")){
  8. System.out.println(toNumber(s));
  9. }else {
  10. System.out.println(toIp(s));
  11. }
  12. }
  13. }
  14. private static String toIp(String str){
  15. Long num = Long.parseLong(str);
  16. String res = Long.toBinaryString(num);
  17. StringBuffer sf = new StringBuffer();
  18. if(res.length() != 32){
  19. for(int i = 0; i < 32 - res.length(); i++ ){
  20. sf.append("0");
  21. }
  22. }
  23. sf.append(res);
  24. String s = sf.toString();
  25. StringBuffer sf1 = new StringBuffer();
  26. return toIp2(s,0,8,sf1);
  27. }
  28. private static String toIp2(String str,int l,int r, StringBuffer sf1){
  29. String s = str.substring(l,r);
  30. Long num = Long.parseLong(s,2);
  31. if(r == str.length()){
  32. sf1.append(num);
  33. }else {
  34. sf1.append(num + ".");
  35. toIp2(str,r,r+8,sf1);
  36. }
  37. return sf1.toString();
  38. }
  39. private static Long toNumber(String str){
  40. String[] s = str.split("\\.");
  41. StringBuffer sf = new StringBuffer();
  42. for(String s1 : s){
  43. Long num = Long.parseLong(s1);
  44. String res = Long.toBinaryString(num);
  45. if(res.length() < 8){
  46. for(int i = 0; i < 8 - res.length(); i++){
  47. sf.append("0");
  48. }
  49. }
  50. sf.append(res);
  51. }
  52. return Long.parseLong(sf.toString(),2);
  53. }
  54. }

(5) HJ101.输入整型数组和排序标识

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. while(in.hasNext()){
  6. int n = in.nextInt();
  7. int[] nums = new int[n];
  8. for(int i = 0; i < n; i++){
  9. nums[i] = in.nextInt();
  10. }
  11. int flag = in.nextInt();
  12. Arrays.sort(nums);
  13. if(flag == 0){
  14. for(int i = 0; i < n; i++){
  15. System.out.print(nums[i] + " ");
  16. }
  17. System.out.println();
  18. } else {
  19. for(int i = n - 1; i >= 0; i--){
  20. System.out.print(nums[i] + " ");
  21. }
  22. System.out.println();
  23. }
  24. }
  25. }
  26. }

(6) *HJ106.字符串逆序

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. String s = in.nextLine();
  6. String[] str = s.split(" ");
  7. for(int i = 0; i < str.length; i++){
  8. if(str[i].length() > 1){
  9. StringBuffer sf = new StringBuffer();
  10. sf.append(str[i]);
  11. str[i] = sf.reverse().toString();
  12. }
  13. }
  14. for(int i = str.length -1; i >= 0 ; i--){
  15. System.out.print(str[i] + " ");
  16. }
  17. }
  18. }

3. 排序5题)

(1) HJ8.合并表记录

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. while(in.hasNext()){
  6. int n = in.nextInt();
  7. TreeMap<Integer,Integer> map = new TreeMap();
  8. for(int i = 0; i < n; i++){
  9. int a = in.nextInt();
  10. int b = in.nextInt();
  11. map.put(a,map.getOrDefault(a,0) + b);
  12. }
  13. map.forEach((key,value) -> {
  14. System.out.println(key+" "+value);
  15. });
  16. }
  17. }
  18. }

(2) *HJ14.字符串排序

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. List<String> list = new ArrayList();
  6. while(in.hasNext()){
  7. int n = in.nextInt();
  8. for(int i = 0; i < n; i++){
  9. list.add(in.next());
  10. }
  11. Collections.sort(list);
  12. for(String s : list){
  13. System.out.println(s);
  14. }
  15. }
  16. }
  17. }

(3) HJ27.查找兄弟单词

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. String[] s = in.nextLine().split(" ");
  6. int n = Integer.parseInt(s[0]);
  7. String x = s[s.length - 2];
  8. int k = Integer.parseInt(s[s.length - 1]);
  9. List<String> list = new ArrayList();
  10. for(String str : s){
  11. if(isBrother(str,x)){
  12. list.add(str);
  13. }
  14. }
  15. int size = list.size();
  16. System.out.println(size);
  17. if(size >= k){
  18. Collections.sort(list);
  19. System.out.println(list.get(k - 1));
  20. }
  21. }
  22. private static boolean isBrother(String str,String x){
  23. if(str.equals(x) || str.length() != x.length()){
  24. return false;
  25. }
  26. char[] c = str.toCharArray();
  27. char[] ch = x.toCharArray();
  28. Arrays.sort(c);
  29. Arrays.sort(ch);
  30. return String.valueOf(c).equals(String.valueOf(ch));
  31. }
  32. }

(4) *NC37.合并区间

  1. import java.util.*;
  2. /**
  3. * Definition for an interval.
  4. * public class Interval {
  5. * int start;
  6. * int end;
  7. * Interval() { start = 0; end = 0; }
  8. * Interval(int s, int e) { start = s; end = e; }
  9. * }
  10. */
  11. public class Solution {
  12. public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
  13. ArrayList<Interval> res = new ArrayList();
  14. int size = intervals.size();
  15. if(size == 0){
  16. return res;
  17. }
  18. Collections.sort(intervals,new Comparator<Interval>(){
  19. public int compare(Interval o1, Interval o2){
  20. if(o1.start != o2.start){
  21. // 头升序
  22. return o1.start - o2.start;
  23. } else {
  24. // 尾升序
  25. return o1.end - o2.end;
  26. }
  27. }
  28. });
  29. res.add(intervals.get(0));
  30. int count = 0;
  31. for(int i = 1; i < size; i++){
  32. Interval o1 = intervals.get(i);
  33. Interval o2 = res.get(count);
  34. if(o1.start <= o2.end){
  35. if(o2.end < o1.end){
  36. o2.end = o1.end;
  37. }
  38. } else{
  39. res.add(o1);
  40. count++;
  41. }
  42. }
  43. return res;
  44. }
  45. }

(5) *HJ68.成绩排序

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. while(in.hasNext()){
  6. int n = in.nextInt();
  7. int flag = in.nextInt();
  8. String[] names = new String[n];
  9. int[] grades = new int[n];
  10. for(int i = 0; i < n; i++){
  11. names[i] = in.next();
  12. grades[i] = Integer.parseInt(in.next());
  13. }
  14. if(flag == 0){
  15. for(int i = 0; i<n; i++){
  16. for(int j = 0; j < n-1-i; j++){
  17. if(grades[j] < grades[j+1]){
  18. int g = grades[j];
  19. grades[j] = grades[j+1];
  20. grades[j+1] = g;
  21. String name = names[j];
  22. names[j] = names[j+1];
  23. names[j+1] = name;
  24. }
  25. }
  26. }
  27. }else {
  28. for(int i = 0; i<n; i++){
  29. for(int j = 0; j < n-1-i; j++){
  30. if(grades[j] > grades[j+1]){
  31. int g = grades[j];
  32. grades[j] = grades[j+1];
  33. grades[j+1] = g;
  34. String name = names[j];
  35. names[j] = names[j+1];
  36. names[j+1] = name;
  37. }
  38. }
  39. }
  40. }
  41. for(int i = 0; i< n; i++){
  42. System.out.println(names[i] + " " + grades[i]);
  43. }
  44. }
  45. }
  46. }

4.栈(2题)

(1) NC52.括号序列

  1. import java.util.*;
  2. public class Solution {
  3. /**
  4. *
  5. * @param s string字符串
  6. * @return bool布尔型
  7. */
  8. public boolean isValid (String s) {
  9. // write code here
  10. if(s.length() < 2){
  11. return false;
  12. }
  13. Stack<Character> st = new Stack();
  14. for(int i = 0; i < s.length(); i++){
  15. if(s.charAt(i) == '('){
  16. st.push(')');
  17. }
  18. else if(s.charAt(i) == '['){
  19. st.push(']');
  20. }
  21. else if(s.charAt(i) == '{'){
  22. st.push('}');
  23. }
  24. else if(st.isEmpty() || st.pop() != s.charAt(i)){
  25. return false;
  26. }
  27. }
  28. return st.isEmpty();
  29. }
  30. }

(2) *leetcode 1614.括号的最大嵌套深度

  1. class Solution {
  2. public int maxDepth(String s) {
  3. Stack<Character> st = new Stack();
  4. int max = 0;
  5. for(int i = 0; i < s.length(); i++){
  6. if(s.charAt(i) == '('){
  7. st.push(')');
  8. }
  9. else if(s.charAt(i) == ')'){
  10. max = Math.max(max,st.size());
  11. st.pop();
  12. }
  13. }
  14. return max;
  15. }
  16. }

5. 排列组合(2题) 递归+回溯(dfs)

(1) *leetcode 面试题08.08.有重复字符串的排列组合

  1. class Solution {
  2. public String[] permutation(String S) {
  3. List<String> list = new ArrayList();
  4. char[] c = S.toCharArray();
  5. Arrays.sort(c);
  6. boolean[] used = new boolean[c.length];
  7. dfs(list,new StringBuilder(),used,c);
  8. String[] str = new String[list.size()];
  9. for(int i = 0; i < str.length; i++){
  10. str[i] = list.get(i);
  11. }
  12. return str;
  13. }
  14. public void dfs(List<String> list,StringBuilder sb, boolean[] used, char[] c){
  15. if(sb.length() == c.length){
  16. list.add(sb.toString());
  17. return;
  18. }
  19. for(int i = 0; i < c.length; i++){
  20. // 第i个字符未被使用
  21. if(!used[i]){
  22. //i大于0 且 第 i-1个字符跟第i个字符相同 且 第i-1个字符未被使用
  23. if(i > 0 && c[i] == c[i-1] && !used[i - 1]){
  24. continue;
  25. } else {
  26. sb.append(c[i]);
  27. used[i] = true;
  28. dfs(list,sb,used,c);
  29. used[i] = false;
  30. sb.deleteCharAt(sb.length() - 1);
  31. }
  32. }
  33. }
  34. }
  35. }

(2) leetcode 77.组合

  1. class Solution {
  2. public List<List<Integer>> combine(int n, int k) {
  3. int[] nums = new int[n];
  4. for(int i = 1; i <= n; i++){
  5. nums[i-1] = i;
  6. }
  7. List<List<Integer>> res = new ArrayList();
  8. dfs(k,res,new ArrayList(),nums,0);
  9. return res;
  10. }
  11. public void dfs(int k,List<List<Integer>> res,List<Integer> list, int[] n, int j){
  12. if(list.size() == k){
  13. List<Integer> l = new ArrayList();
  14. l.addAll(list);
  15. res.add(l);
  16. return;
  17. }
  18. for(int i = j; i < n.length; i++){
  19. list.add(n[i]);
  20. dfs(k,res,list,n,i+1);
  21. list.remove(list.size() - 1);
  22. }
  23. }
  24. }

6. 双指针3题)

(1) *leetcode 674.最长连续递增序列

  1. class Solution {
  2. public int findLengthOfLCIS(int[] nums) {
  3. int max = 1;
  4. int count = 1;
  5. for(int j = 1; j < nums.length; j++){
  6. if(nums[j] > nums[j - 1]){
  7. count++;
  8. }
  9. if(nums[j] <= nums[j - 1] || j == nums.length - 1){
  10. max = Math.max(max,count);
  11. count = 1;
  12. }
  13. }
  14. return max;
  15. }
  16. }

(2) NC17.最长回文子串

  1. import java.util.*;
  2. public class Solution {
  3. public int getLongestPalindrome (String A) {
  4. int n = A.length();
  5. if(n < 2){
  6. return n;
  7. }
  8. int max = 1;
  9. for(int i = 0; i < n; i++){
  10. max = Math.max(max,Math.max(fun(A,i,i),fun(A,i,i+1)));
  11. }
  12. return max;
  13. }
  14. public int fun(String s,int begin,int end){
  15. while(begin >= 0 && end < s.length() && s.charAt(begin) == s.charAt(end)){
  16. begin--;
  17. end++;
  18. }
  19. return end - begin - 1;
  20. }
  21. }

(3) NC28.最小覆盖子串 滑动窗口

  1. import java.util.*;
  2. public class Solution {
  3. public String minWindow (String S, String T) {
  4. if(S.contains(T)){
  5. return T;
  6. }
  7. int cnt = S.length() + 1;
  8. int[] hash = new int[128];
  9. for(int i = 0; i < T.length(); i++){
  10. hash[T.charAt(i)] -= 1;
  11. }
  12. int slow = 0,fast = 0,left = -1,right = -1;
  13. for(; fast< S.length(); fast++){
  14. char c = S.charAt(fast);
  15. hash[c]++;
  16. while(check(hash)){
  17. if(cnt > fast - slow + 1){
  18. cnt = fast - slow + 1;
  19. left = slow;
  20. right = fast;
  21. }
  22. c = S.charAt(slow);
  23. hash[c]--;
  24. slow++;
  25. }
  26. }
  27. if(left == -1){
  28. return "";
  29. }
  30. return S.substring(left,right + 1);
  31. }
  32. public boolean check(int[] hash){
  33. for(int i = 0; i < hash.length; i++){
  34. if(hash[i] < 0){
  35. return false;
  36. }
  37. }
  38. return true;
  39. }
  40. }

7. 深搜1题)

(1) HJ41.称砝码

  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. public class Main {
  4. public static void main(String[] args) throws Exception {
  5. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  6. String line;
  7. while ((line = reader.readLine()) != null) {
  8. int n = Integer.parseInt(line);
  9. String[] s = reader.readLine().split(" ");
  10. String[] s2 = reader.readLine().split(" ");
  11. int[] weight = new int[n];
  12. int[] number = new int[n];
  13. for (int i = 0; i < n; i++) {
  14. weight[i] = Integer.parseInt(s[i]);
  15. number[i] = Integer.parseInt(s2[i]);
  16. }
  17. boolean[] exist = new boolean[200000];
  18. int[] arr = new int[20000];
  19. arr[0]++;
  20. for (int i = 0; i < n; i++) {
  21. for (int j = 0; j < number[i]; j++) {
  22. int index = arr[0];
  23. if (!exist[weight[i]]) {
  24. exist[weight[i]] = true;
  25. arr[++arr[0]] = weight[i];
  26. }
  27. for (int k = 1; k <= index; k++) {
  28. int sum = arr[k] + weight[i];
  29. if (!exist[sum]) {
  30. exist[sum] = true;
  31. arr[++arr[0]] = sum;
  32. }
  33. }
  34. }
  35. }
  36. System.out.println(arr[0]);
  37. }
  38. }
  39. }

8. 二叉树(2题)队列

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int[] levelOrder(TreeNode root) {
  12. if(root == null) return new int[0];
  13. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  14. List<Integer> list = new ArrayList();
  15. queue.add(root);
  16. while(!queue.isEmpty()){
  17. TreeNode node = queue.poll();
  18. list.add(node.val);
  19. if(node.left != null){
  20. queue.add(node.left);
  21. }
  22. if(node.right != null){
  23. queue.add(node.right);
  24. }
  25. }
  26. return list.stream().mapToInt(Integer::intValue).toArray();
  27. }
  28. }

(1) *leetcode 剑指offer 32 — II.从上到下打印二叉树II

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public List<List<Integer>> levelOrder(TreeNode root) {
  12. List<List<Integer>> res = new ArrayList();
  13. if(root == null) return res;
  14. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  15. queue.add(root);
  16. while(!queue.isEmpty()){
  17. List<Integer> list = new ArrayList();
  18. int size = queue.size();
  19. for(;size > 0; size--){
  20. TreeNode node = queue.poll();
  21. if(node != null){
  22. list.add(node.val);
  23. if(node.left != null){
  24. queue.add(node.left);
  25. }
  26. if(node.right != null){
  27. queue.add(node.right);
  28. }
  29. }
  30. }
  31. res.add(list);
  32. }
  33. return res;
  34. }
  35. }

(2) leetcode 剑指offer 32 — III.从上到下打印二叉树III

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public List<List<Integer>> levelOrder(TreeNode root) {
  12. List<List<Integer>> res = new ArrayList();
  13. if(root == null) return res;
  14. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  15. queue.add(root);
  16. while(!queue.isEmpty()){
  17. List<Integer> list = new ArrayList();
  18. int size = queue.size();
  19. for(;size > 0; size--){
  20. TreeNode node = queue.poll();
  21. if(node != null){
  22. list.add(node.val);
  23. if(node.left != null){
  24. queue.add(node.left);
  25. }
  26. if(node.right != null){
  27. queue.add(node.right);
  28. }
  29. }
  30. }
  31. res.add(list);
  32. }
  33. for(int i=1;i<res.size();i+=2){
  34. Collections.reverse(res.get(i));
  35. }
  36. return res;
  37. }
  38. }

9. 其他6题)

(1) *HJ108.求最小公倍数

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner in=new Scanner(System.in);
  5. int a=in.nextInt();
  6. int b=in.nextInt();
  7. System.out.println(a*b/gcd(a,b));
  8. }
  9. private static int gcd(int a, int b) {
  10. return b==0?a:gcd(b,a%b);
  11. }
  12. }

(2) *HJ28.素数伴侣

  1. import java.util.*;
  2. public class Main {
  3. //这里包含了判断素数的方法
  4. //小技巧!!!素数不是偶数,那么和是素数的话就是奇数+偶数
  5. //那么可以分成两堆,一堆偶数,一堆奇数
  6. //匈牙利算法,先到先得 能让就让
  7. //有机会上,没机会创造机会也要上
  8. public static void main(String[] args) {
  9. // TODO Auto-generated method stub
  10. Scanner scan = new Scanner(System.in);
  11. while(scan.hasNext()){
  12. int n = scan.nextInt();
  13. int[] tempArray = new int[n];
  14. for(int i = 0; i < n; i++){
  15. tempArray[i] = scan.nextInt();
  16. }
  17. ArrayList<Integer> evens = new ArrayList<Integer>();
  18. ArrayList<Integer> odds = new ArrayList<Integer>();
  19. for(int i = 0; i < n; i++) {
  20. if((tempArray[i] & 1) != 1) {
  21. evens.add(tempArray[i]);
  22. }else {
  23. odds.add(tempArray[i]);
  24. }
  25. }
  26. //下面开始才是重头戏
  27. //用于标记那个奇数匹配了偶数,直接记录奇数的值,而不是奇数在奇数数组中的下标
  28. int[] evensMatch =new int[evens.size()];
  29. int result = 0;
  30. //遍历奇数去匹配偶数
  31. for(int i = 0; i < odds.size(); i++) {
  32. //每一步重新创建,也就是相当于清空
  33. //used数组用于标记某个某数位置是否
  34. int[] used = new int[evens.size()];
  35. //这里采用了匈牙利算法,先到先得
  36. if(find(odds.get(i), evens, used, evensMatch)) {
  37. result++;
  38. }
  39. }
  40. System.out.println(result);
  41. }
  42. }
  43. public static boolean isPrime(int num) {
  44. for(int i = 2; i <= Math.sqrt(num); i++) {
  45. if(num % i == 0) {
  46. return false;
  47. }
  48. }
  49. return true;
  50. }
  51. public static boolean find(int x, ArrayList<Integer> evens,int[] used, int[] evensMatch) {
  52. //遍历偶数
  53. //去检查当前传入的奇数能否与偶数哪些数匹配
  54. for(int i = 0; i < evens.size(); i++) {
  55. //如果当前偶数与传入的奇数匹配,并且当前偶数位还没有匹配过奇数
  56. if(isPrime(x + evens.get(i)) && used[i] == 0) {
  57. //设置当前偶数位匹配为true,也就是 1
  58. used[i] = 1;
  59. //如果第i个偶数没有伴侣
  60. //或者第i个偶数原来有伴侣,并且该伴侣能够重新找到伴侣的话(这里有递归调用)
  61. //则奇数x可以设置为第i个偶数的伴侣
  62. //这里采用了匈牙利算法,能让则让
  63. if(evensMatch[i] == 0 || find(evensMatch[i], evens, used, evensMatch)) {
  64. evensMatch[i] = x;
  65. return true;
  66. }
  67. }
  68. }
  69. //遍历完偶数都没有可以与传入奇数做伴侣的,该奇数只能孤独终老了
  70. return false;
  71. }
  72. }

(3) *HJ60.查找组成一个偶数最接近的两个素数

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. int n = in.nextInt();
  6. int i = n/2;
  7. for(;i < n; i += 2){
  8. if(i % 2 == 0 && i != 2){
  9. i++;
  10. }
  11. if(isPrime(n - i) && isPrime(i)){
  12. System.out.println(n - i);
  13. System.out.println(i);
  14. break;
  15. }
  16. }
  17. }
  18. public static boolean isPrime(int num) {
  19. for(int i = 2; i <= Math.sqrt(num); i++) {
  20. if(num % i == 0) {
  21. return false;
  22. }
  23. }
  24. return true;
  25. }
  26. }

(4) *leetcode 994.腐烂的橘子 (BFS 广度搜索)

  1. class Solution {
  2. public int orangesRotting(int[][] grid) {
  3. int M = grid.length;
  4. int N = grid[0].length;
  5. Queue<int[]> queue = new LinkedList<>();
  6. int count = 0; // count 表示新鲜橘子的数量
  7. for (int r = 0; r < M; r++) {
  8. for (int c = 0; c < N; c++) {
  9. if (grid[r][c] == 1) {
  10. count++;
  11. } else if (grid[r][c] == 2) {
  12. queue.add(new int[]{r, c});
  13. }
  14. }
  15. }
  16. int round = 0; // round 表示腐烂的轮数,或者分钟数
  17. while (count > 0 && !queue.isEmpty()) {
  18. round++;
  19. int n = queue.size();
  20. for (int i = 0; i < n; i++) {
  21. int[] orange = queue.poll();
  22. int r = orange[0];
  23. int c = orange[1];
  24. if (r-1 >= 0 && grid[r-1][c] == 1) {
  25. grid[r-1][c] = 2;
  26. count--;
  27. queue.add(new int[]{r-1, c});
  28. }
  29. if (r+1 < M && grid[r+1][c] == 1) {
  30. grid[r+1][c] = 2;
  31. count--;
  32. queue.add(new int[]{r+1, c});
  33. }
  34. if (c-1 >= 0 && grid[r][c-1] == 1) {
  35. grid[r][c-1] = 2;
  36. count--;
  37. queue.add(new int[]{r, c-1});
  38. }
  39. if (c+1 < N && grid[r][c+1] == 1) {
  40. grid[r][c+1] = 2;
  41. count--;
  42. queue.add(new int[]{r, c+1});
  43. }
  44. }
  45. }
  46. if (count > 0) {
  47. return -1;
  48. } else {
  49. return round;
  50. }
  51. }
  52. }

(5) leetcode 204.计数质数

  1. class Solution {
  2. public int countPrimes(int n) {
  3. boolean[] isPrim = new boolean[n];
  4. Arrays.fill(isPrim, true);
  5. // 从 2 开始枚举到 sqrt(n)。
  6. for (int i = 2; i * i < n; i++) {
  7. // 如果当前是素数
  8. if (isPrim[i]) {
  9. // 就把从 i*i 开始,i 的所有倍数都设置为 false。
  10. for (int j = i * i; j < n; j+=i) {
  11. isPrim[j] = false;
  12. }
  13. }
  14. }
  15. // 计数
  16. int cnt = 0;
  17. for (int i = 2; i < n; i++) {
  18. if (isPrim[i]) {
  19. cnt++;
  20. }
  21. }
  22. return cnt;
  23. }
  24. }

(6) HJ25. 数据分类处理

  1. jimport java.util.*;
  2. public class Main {
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. int n = in.nextInt();
  6. String str = in.nextLine();
  7. String[] strs = str.split(" ");
  8. int r = in.nextInt();
  9. Set<Integer> set = new TreeSet();
  10. for(int i = 0; i < r; i++){
  11. set.add(in.nextInt());
  12. }
  13. List<String> res = new ArrayList();
  14. List<String> list = new ArrayList();
  15. for(Integer s : set){
  16. if(str.contains(String.valueOf(s))){
  17. res.add(String.valueOf(s));
  18. int count = 0;
  19. for(int i = 0;i < strs.length; i++){
  20. if(strs[i].contains(String.valueOf(s))){
  21. count++;
  22. list.add(String.valueOf(i - 1));
  23. list.add(strs[i]);
  24. }
  25. }
  26. res.add(String.valueOf(count));
  27. res.addAll(list);
  28. list.clear();
  29. }
  30. }
  31. System.out.print(res.size() + " ");
  32. for(String s1 : res){
  33. System.out.print(s1 + " ");
  34. }
  35. }
  36. }

面试手撕代码

(1)递归:NC68.跳台阶

  1. public class Solution {
  2. public int jumpFloor(int target) {
  3. if(target == 1 || target == 0){
  4. return 1;
  5. }
  6. if(target == 2){
  7. return 2;
  8. }
  9. return jumpFloor(target - 1) + jumpFloor(target - 2);
  10. }
  11. }
  1. import java.util.*;
  2. public class Solution {
  3. Map<Integer,Integer> map = new HashMap();
  4. public int jumpFloor(int target) {
  5. if(target == 1 || target == 0){
  6. return 1;
  7. }
  8. if(target == 2){
  9. return 2;
  10. }
  11. if(map.containsKey(target)){
  12. return map.get(target);
  13. } else{
  14. map.put(target,jumpFloor(target - 1) + jumpFloor(target - 2));
  15. return map.get(target);
  16. }
  17. }
  18. }

(2)猴子爬山

  1. import java.util.*;
  2. public class Solution {
  3. Map<Integer,Integer> map = new HashMap();
  4. public int jumpFloor(int target) {
  5. if(target == 1 && target == 2){
  6. return 1;
  7. }
  8. if(target == 3){
  9. return 2;
  10. }
  11. if(map.containsKey(target)){
  12. return map.get(target);
  13. } else{
  14. map.put(target,jumpFloor(target - 1) + jumpFloor(target - 3));
  15. return map.get(target);
  16. }
  17. }
  18. }

(3)输出字符串出现次数最少的字符

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. String s = in.next();
  6. Map<Character,Integer> map = new HashMap();
  7. for(char c : s.toCharArray()){
  8. map.put(c,map.getOrDefault(c,1)+1);
  9. }
  10. int min = Integer.MAX_VALUE;
  11. for(int i : map.values()){
  12. min = Math.min(min,i);
  13. }
  14. for(char c : s.toCharArray()){
  15. if(map.get(c) == min){
  16. System.out.print(c);
  17. }
  18. }
  19. }
  20. }

(4)正方形矩阵顺时针旋转90度

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args){
  4. Scanner in = new Scanner(System.in);
  5. while(in.hasNext()){
  6. int n = in.nextInt();
  7. int[][] nums = new int[n][n];
  8. for(int i = 0; i < n; i++){
  9. for(int j = 0; j < n; j++){
  10. nums[i][j] = in.nextInt();
  11. }
  12. }
  13. //对角线翻转
  14. for(int i = 0; i < n; i++){
  15. for(int j = 0; j < i; j++){
  16. nums[i][j] = nums[i][j] ^ nums[j][i];
  17. nums[j][i] = nums[j][i] ^ nums[i][j];
  18. nums[i][j] = nums[j][i] ^ nums[i][j];
  19. }
  20. }
  21. // 中轴线翻转
  22. for(int i = 0; i < n; i++){
  23. for(int j = 0; j < n/2; j++){
  24. nums[i][j] = nums[i][j] ^ nums[i][n-j-1];
  25. nums[i][n-j-1] = nums[i][n-j-1] ^ nums[i][j];
  26. nums[i][j] = nums[i][n-j-1] ^ nums[i][j];
  27. }
  28. }
  29. // 输出
  30. for(int i = 0; i < n; i++){
  31. for(int j = 0; j < n; j++)
  32. System.out.print(nums[i][j] + " ");
  33. System.out.println();
  34. }
  35. }
  36. }
  37. }

  1. import java.util.*;
  2. public class Solution {
  3. public int[][] rotateMatrix(int[][] mat, int n) {
  4. // 对角线对折
  5. for(int i = 0; i < n; i++){
  6. for(int j = 0; j < i; j++){
  7. mat[i][j] = mat[i][j] ^ mat[j][i];
  8. mat[j][i] = mat[i][j] ^ mat[j][i];
  9. mat[i][j] = mat[i][j] ^ mat[j][i];
  10. }
  11. }
  12. // 中轴线对折
  13. for(int i = 0; i < n; i++){
  14. for(int j = 0; j < n/2; j++){
  15. mat[i][j] = mat[i][j] ^ mat[i][n-j-1];
  16. mat[i][n-j-1] = mat[i][j] ^ mat[i][n-j-1];
  17. mat[i][j] = mat[i][j] ^ mat[i][n-j-1];
  18. }
  19. }
  20. return mat;
  21. }
  22. }

(5)链表逆序

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }*/
  9. public class Solution {
  10. public ListNode ReverseList(ListNode head) {
  11. ListNode pre = null;
  12. ListNode next = null;
  13. while(head != null){
  14. next = head.next;
  15. head.next = pre;
  16. pre = head;
  17. head = next;
  18. }
  19. return pre;
  20. }
  21. }

(6)租房信息查询系统

int instance = Math.abs(x1-x2)+Math.abs(y1-y2);

(7)最长公共前缀

  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if(strs.length == 0) return "";
  4. String s = strs[0];
  5. for(String st : strs){
  6. while(!st.startsWith(s)){
  7. if(s.length() == 0) return "";
  8. s = s.substring(0,s.length()-1);
  9. }
  10. }
  11. return s;
  12. }
  13. }

(8)跳跃游戏I II

  1. class Solution {
  2. public boolean canJump(int[] nums) {
  3. int n = 1;
  4. for(int i = nums.length - 2; i >= 0; i--){
  5. if(nums[i] >= n){
  6. n = 1;
  7. }else{
  8. n++;
  9. }
  10. if(i == 0 && n > 1){
  11. return false;
  12. }
  13. }
  14. return true;
  15. }
  16. }

  1. class Solution {
  2. public int jump(int[] nums) {
  3. int max = 0;
  4. int end = 0;
  5. int step = 0;
  6. for(int i = 0; i < nums.length - 1; i++){
  7. max = Math.max(max, nums[i] + i);
  8. if (i == end){
  9. end = max;
  10. step++;
  11. }
  12. }
  13. return step;
  14. }
  15. }

(9)盛最多水的容器

  1. class Solution {
  2. public int maxArea(int[] height) {
  3. int max = 0;
  4. for(int i = 0, j = height.length - 1; i < j;){
  5. int minHeight = height[i] < height[j] ? height[i++] : height[j--];
  6. max = Math.max(max,(j - i + 1) * minHeight);
  7. }
  8. return max;
  9. }
  10. }

(10)字典序排数

  1. class Solution {
  2. public List<Integer> lexicalOrder(int n) {
  3. List<String> nums = new ArrayList();
  4. for(int i = 0; i < n; i++){
  5. nums.add(String.valueOf(i+1));
  6. }
  7. Collections.sort(nums);
  8. List<Integer> num = new ArrayList();
  9. for(int i = 0; i < n; i++){
  10. num.add(Integer.parseInt(nums.get(i)));
  11. }
  12. return num;
  13. }
  14. }
  1. class Solution {
  2. List<Integer> ans = new ArrayList<>();
  3. public List<Integer> lexicalOrder(int n) {
  4. for (int i = 1; i <= 9; i++) dfs(i, n);
  5. return ans;
  6. }
  7. void dfs(int cur, int limit) {
  8. if (cur > limit) return ;
  9. ans.add(cur);
  10. for (int i = 0; i <= 9; i++) dfs(cur * 10 + i, limit);
  11. }
  12. }
  1. class Solution {
  2. public List<Integer> lexicalOrder(int n) {
  3. List<Integer> ans = new ArrayList<>();
  4. for (int i = 0, j = 1; i < n; i++) {
  5. ans.add(j);
  6. if (j * 10 <= n) {
  7. j *= 10;
  8. } else {
  9. while (j % 10 == 9 || j + 1 > n) j /= 10;
  10. j++;
  11. }
  12. }
  13. return ans;
  14. }
  15. }

(11)消除游戏

  1. class Solution {
  2. public int lastRemaining(int n) {
  3. int head = 1;
  4. int step = 1;
  5. boolean left = true;
  6. while (n > 1) {
  7. //从左边开始移除 or(从右边开始移除,数列总数为奇数)
  8. if (left || n % 2 != 0) {
  9. head += step;
  10. }
  11. step *= 2; //步长 * 2
  12. left = !left; //取反移除方向
  13. n /= 2; //总数 / 2
  14. }
  15. return head;
  16. }
  17. }

(12)验证回文串

  1. class Solution {
  2. public boolean isPalindrome(String s) {
  3. StringBuilder sb = new StringBuilder();
  4. for(char c : s.toCharArray()){
  5. if(Character.isLetterOrDigit(c)){
  6. sb.append(Character.toLowerCase(c));
  7. }
  8. }
  9. String s_re = new StringBuilder(sb).reverse().toString();
  10. return sb.toString().equals(s_re);
  11. }
  12. }

(13)最长回文子串

  1. class Solution {
  2. public String longestPalindrome(String s) {
  3. int n = s.length();
  4. if(n < 2) return s;
  5. int start = 0, end = 0;
  6. for(int i = 0; i < n; i++){
  7. int max = Math.max(fun(s,i,i),fun(s,i,i+1));
  8. if(max > end - start){
  9. start = i - (max - 1) / 2;
  10. end = i + max / 2;
  11. }
  12. }
  13. return s.substring(start,end+1);
  14. }
  15. public int fun(String s,int begin,int end){
  16. while(begin >= 0 && end < s.length() && s.charAt(begin) == s.charAt(end)){
  17. begin--;
  18. end++;
  19. }
  20. return end - begin - 1;
  21. }
  22. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/612081
推荐阅读
相关标签
  

闽ICP备14008679号