LeetCode之常用函数

[复制链接]
发表于 2026-1-25 01:12:26 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
 网络了 LeetCode 口试经典150 & LeetCode 热题100中常用的函数与本领
   LeetCode之数组/字符串

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. 数组排序
  3.         int[] array = new int[]{3, 7, 5, 2};
  4.         Arrays.sort(array);
  5.         // 结果: [2, 3, 5, 7]
  6.         System.out.println(Arrays.toString(array));
  7.         // 2. 数组拷贝
  8.         int[] arrayOld = new int[]{1, 2, 3, 4, 5};
  9.         int[] arrayNew = new int[5];
  10.         System.arraycopy(arrayOld, 0, arrayNew, 0, arrayOld.length - 1);
  11.         // 结果: [1, 2, 3, 4, 5]
  12.         System.out.println(Arrays.toString(arrayOld));
  13.         // 结果: [1, 2, 3, 4, 0]
  14.         System.out.println(Arrays.toString(arrayNew));
  15.         // 3. 最大值最小值
  16.         int max = Math.max(2, 3);
  17.         int min = Math.min(2, 3);
  18.         // 结果 3-2
  19.         System.out.println(max + "-" + min);
  20.         // 4. 随机数生成
  21.         Random random = new Random();
  22.         int randomInt = random.nextInt(10);
  23.         // 结果: 8
  24.         System.out.println(randomInt);
  25.         // 5. HashMap
  26.         Map<String, String> hashMap = Maps.newHashMap();
  27.         hashMap.put("1", "1");
  28.         hashMap.put("2", "2");
  29.         hashMap.put("3", "3");
  30.         // 结果: true
  31.         System.out.println(hashMap.containsKey("1"));
  32.         // 6. ArrayList
  33.         List<String> arrayList = Lists.newArrayList("1", "2", "3");
  34.         arrayList.set(2, "4");
  35.         arrayList.remove(1);
  36.         // 结果: [1, 4]
  37.         System.out.println(arrayList);
  38.         // 7. 数组创建
  39.         int[] arr1 = new int[3];
  40.         arr1[0] = 1;
  41.         int[] arr2 = {1, 2, 3};
  42.         int[] arr3 = new int[]{1,2,3};
  43.         // 结果: [1, 0, 0]
  44.         System.out.println(Arrays.toString(arr1));
  45.         // 结果: [1, 2, 3]
  46.         System.out.println(Arrays.toString(arr2));
  47.         // 结果: [1, 2, 3]
  48.         System.out.println(Arrays.toString(arr3));
  49.         // 8. 字符串
  50.         String str = "hello world";
  51.         char[] charArray = str.toCharArray();
  52.         // 结果: l
  53.         System.out.println(str.charAt(3));
  54.         // 结果: [h, e, l, l, o,  , w, o, r, l, d]
  55.         System.out.println(Arrays.toString(charArray));
  56.         // 9. switch语句
  57.         String condition = "a";
  58.         // 结果: a
  59.         switch (condition) {
  60.             case "a":
  61.                 System.out.println("a");
  62.                 break;
  63.             case "b":
  64.                 System.out.println("b");
  65.                 break;
  66.             default:
  67.                 System.out.println("c");
  68.         }
  69.         // 10. 可变字符串
  70.         StringBuilder sb = new StringBuilder();
  71.         sb.append("1");
  72.         sb.append("2");
  73.         sb.append("3");
  74.         // 结果: 123
  75.         System.out.println(sb.toString());
  76.         // 11. 字符串去空格
  77.         String strTrim = " tes t ";
  78.         String trim = strTrim.trim();
  79.         // 结果: tes t
  80.         System.out.println(trim);
  81.         // 结果: 5
  82.         System.out.println(strTrim.lastIndexOf("t"));
  83.         // 12. 字符串截取
  84.         String strSub = "test subString";
  85.         String substring = strSub.substring(5, 8);
  86.         System.out.println(substring);
  87.         // 13. 正则&字符串拼接
  88.         String string = " hello world ";
  89.         String trim1 = string.trim();
  90.         // 结果: hello world
  91.         System.out.println(trim1);
  92.         String[] split = trim1.split("\\s+");
  93.         List<String> strings = Arrays.asList(split);
  94.         // 结果: [hello, world]
  95.         System.out.println(strings);
  96.         Collections.reverse(strings);
  97.         // 结果: [world, hello]
  98.         System.out.println(strings);
  99.         // 结果: world,hello
  100.         String join = String.join(",", strings);
  101.         System.out.println(join);
  102.     }
复制代码
LeetCode之双指针

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. Char操作
  3.         char a = '1';
  4.         char b = 'b';
  5.         // 判断是否字符或数组
  6.         // 结果: true
  7.         System.out.println(Character.isLetter(b));
  8.         // 结果: true
  9.         System.out.println(Character.isDigit(a));
  10.         // 结果: true
  11.         System.out.println(Character.isLetterOrDigit(a));
  12.         char c = 'C';
  13.         // 结果: true
  14.         System.out.println(Character.toLowerCase(c));
  15.         // 2. 可变字符串反转
  16.         StringBuilder sb = new StringBuilder();
  17.         sb.append("1");
  18.         sb.append("2");
  19.         sb.append("3");
  20.         // 结果: 321
  21.         System.out.println(sb.reverse());
  22.     }
复制代码
LeetCode之滑动窗口

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. Integer最大最小值
  3.         int min = Integer.MIN_VALUE;
  4.         int max = Integer.MAX_VALUE;
  5.         // 结果: -2147483648
  6.         System.out.println(min);
  7.         // 结果: 2147483648
  8.         System.out.println(max);
  9.         // 2. Set操作
  10.         Set<String> set = Sets.newHashSet("1", "2", "2", "3");
  11.         // 结果: [1, 2, 3]
  12.         System.out.println(set);
  13.         // 结果: true
  14.         System.out.println(set.contains("2"));
  15.         // 结果: true
  16.         System.out.println(set.remove("3"));
  17.         // 结果: [1, 2]
  18.         System.out.println(set);
  19.     }
复制代码
LeetCode之矩阵

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. 字母索引
  3.         char a = 'a';
  4.         char b = 'b';
  5.         // 结果: 49
  6.         System.out.println(a - '0');
  7.         // 结果: 50
  8.         System.out.println(b - '0');
  9.         // 2. 深拷贝
  10.         int[] aArr = new int[]{1, 2, 3};
  11.         int[] clone = aArr.clone();
  12.         clone[0] = 11;
  13.         // 结果: [1, 2, 3]
  14.         System.out.println(Arrays.toString(aArr));
  15.         // 结果: [11, 2, 3]
  16.         System.out.println(Arrays.toString(clone));
  17.     }
复制代码
LeetCode之哈希表

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. Map操作
  3.         Map<Integer, String> map = new HashMap<>();
  4.         map.put(1, "1");
  5.         map.put(2, "2");
  6.         // 结果: 3
  7.         System.out.println(map.getOrDefault(3, "3"));
  8.         // 结果: true
  9.         System.out.println(map.containsKey(1));
  10.         Collection<String> values = map.values();
  11.         // 结果: [1, 2]
  12.         System.out.println(values);
  13.         List<String> list = new ArrayList<>(values);
  14.         // 结果: [1, 2]
  15.         System.out.println(list);
  16.         // 2. Set操作
  17.         Set<Integer> set = new HashSet<>();
  18.         set.add(1);
  19.         set.add(2);
  20.         // 结果: true
  21.         System.out.println(set.contains(1));
  22.         // 3. 字符串char操作
  23.         String str = "hello";
  24.         char[] chars = str.toCharArray();
  25.         // 结果: [h, e, l, l, o]
  26.         System.out.println(Arrays.toString(chars));
  27.         // 结果: e
  28.         System.out.println(str.charAt(1));
  29.         // 4. 字符串分割
  30.         String s = "dog cat cat dog";
  31.         String[] s1 = s.split(" ");
  32.         // 结果: [dog, cat, cat, dog]
  33.         System.out.println(Arrays.toString(s1));
  34.         // 5. 最大最小值
  35.         int max = Math.max(2, 3);
  36.         int min = Math.min(1, 2);
  37.         // 结果: 3
  38.         System.out.println(max);
  39.         // 结果: 1
  40.         System.out.println(min);
  41.         // 6. 除法操作
  42.         // 结果: 3
  43.         System.out.println(6 / 2);
  44.         // 结果: 0
  45.         System.out.println(6 % 2);
  46.         // 结果: 2
  47.         System.out.println(5 / 2);
  48.         // 结果: 1
  49.         System.out.println(5 % 2);
  50.     }
复制代码
LeetCode之区间

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. StringBuilder
  3.         StringBuilder sb = new StringBuilder(Integer.toString(1));
  4.         sb.append("2");
  5.         // 结果: 12
  6.         System.out.println(sb.toString());
  7.         // 2. Arrays
  8.         int[] arr = new int[]{3, 1, 2, 4};
  9.         Arrays.sort(arr);
  10.         // 结果: [1, 2, 3, 4]
  11.         System.out.println(Arrays.toString(arr));
  12.         int[][] arr1 = new int[][]{{2, 1}, {1, 2}, {3, 0}};
  13.         // 结果: [[3, 0], [2, 1], [1, 2]]
  14.         Arrays.sort(arr1, (a, b) -> b[0] - a[0]);
  15.         System.out.println(Arrays.deepToString(arr1));
  16.         // 结果: [[1, 2], [2, 1], [3, 0]]
  17.         Arrays.sort(arr1, (a, b) -> a[0] - b[0]);
  18.         System.out.println(Arrays.deepToString(arr1));
  19.         // 3. List
  20.         List<int[]> list = new ArrayList<>();
  21.         list.add(new int[]{1, 2});
  22.         list.add(new int[]{3, 4});
  23.         int[][] arr2 = list.toArray(new int[1][1]);
  24.         // 结果: [[1, 2], [3, 4]]
  25.         System.out.println(Arrays.deepToString(arr2));
  26.     }
复制代码
LeetCode之栈

所在链接
  1. public static void main(String[] args) {
  2.         // 双端队列
  3.         Deque<Character> stack = new ArrayDeque<>();
  4.         stack.push('1');
  5.         stack.push('2');
  6.         // 结果: 2
  7.         System.out.println(stack.peek());
  8.         // 结果: 2
  9.         System.out.println(stack.pop());
  10.         // 结果: false
  11.         System.out.println(stack.isEmpty());
  12.         // 结果: 1
  13.         System.out.println(stack.pop());
  14.         // 结果: true
  15.         System.out.println(stack.isEmpty());
  16.         // Character
  17.         String str = "test";
  18.         char[] chars = str.toCharArray();
  19.         // 结果: t
  20.         System.out.println(str.charAt(0));
  21.         // 结果: [t, e, s, t]
  22.         System.out.println(Arrays.toString(chars));
  23.         // 双端队列
  24.         Deque<Character> deque = new LinkedList<>();
  25.         // 从左右往右offer
  26.         deque.offerFirst('1');
  27.         deque.offerFirst('2');
  28.         deque.offerFirst('3');
  29.         deque.push('4');
  30.         deque.offerLast('5');
  31.         // 结果: [4, 3, 2, 1, 5]
  32.         System.out.println(deque);
  33.         deque.pollFirst();
  34.         // 结果: [3, 2, 1, 5]
  35.         System.out.println(deque);
  36.         deque.pollLast();
  37.         // 结果: [3, 2, 1]
  38.         System.out.println(deque);
  39.         
  40.         // Integer
  41.         String str1 = Integer.toString(1);
  42.         // 结果: 1
  43.         System.out.println(str1);
  44.         int i = Integer.parseInt("2");
  45.         // 结果: 2
  46.         System.out.println(i);
  47.     }
复制代码
LeetCode之链表

所在链接
  1.     static class ListNode {
  2.         // 节点的值
  3.         int val;
  4.         // 指向下一个节点的指针
  5.         ListNode next;
  6.         // 默认构造函数
  7.         ListNode() {}
  8.         // 带值的构造函数
  9.         ListNode(int x) {
  10.             this.val = x;
  11.         }
  12.         // 带值和下一个节点的构造函数
  13.         ListNode(int val, ListNode next) {
  14.             this.val = val;
  15.             this.next = next;
  16.         }
  17.     }
  18.     public static void main(String[] args) {
  19.         // Set
  20.         Set<ListNode> set = new HashSet<>();
  21.         ListNode node1 = new ListNode(1);
  22.         ListNode node2 = new ListNode(2);
  23.         node1.next = node2;
  24.         set.add(node1);
  25.         set.add(node2);
  26.         // 结果: true
  27.         System.out.println(set.contains(node1));
  28.         // dummyNode
  29.         ListNode dummyNode = new ListNode(-1);
  30.         ListNode node3 = new ListNode(3);
  31.         dummyNode.next = node3;
  32.         // 当前节点初始化为哨兵节点
  33.         ListNode cur = dummyNode;
  34.         // 结果: -1
  35.         System.out.println(cur.val);
  36.         // 结果: 3
  37.         System.out.println(cur.next.val);
  38.     }
复制代码
LeetCode之二叉树

所在链接
  1.     static class TreeNode {
  2.         int val;
  3.         TreeNode left;
  4.         TreeNode right;
  5.         TreeNode() {}
  6.         TreeNode(int val) {
  7.             this.val = val;
  8.         }
  9.         TreeNode(int val, TreeNode left, TreeNode right) {
  10.             this.val = val;
  11.             this.left = left;
  12.             this.right = right;
  13.         }
  14.     }
  15.     public static void main(String[] args) {
  16.         TreeNode root = new TreeNode(0);
  17.         TreeNode treeNode1 = new TreeNode(1);
  18.         TreeNode treeNode2 = new TreeNode(2);
  19.         root.left = treeNode1;
  20.         root.right = treeNode2;
  21.     }
复制代码
LeetCode之二叉树条理遍历

所在链接
  1.     public static void main(String[] args) {
  2.         // 队列
  3.         Queue<Integer> queue = new ArrayDeque<>();
  4.         queue.offer(1);
  5.         queue.offer(2);
  6.         queue.offer(3);
  7.         // 结果: [1, 2, 3]
  8.         System.out.println(queue);
  9.         // 结果: 1 左头右尾
  10.         System.out.println(queue.peek());
  11.         // 结果: 1
  12.         System.out.println(queue.poll());
  13.         // 结果: [2, 3]
  14.         System.out.println(queue);
  15.         // 双端队列
  16.         Deque<Integer> deque = new ArrayDeque<>();
  17.         deque.offer(1);
  18.         // 左头右尾
  19.         deque.offerLast(2);
  20.         // 结果: [1, 2]
  21.         System.out.println(deque);
  22.         deque.offerFirst(3);
  23.         // 结果: [3, 1, 2]
  24.         System.out.println(deque);
  25.         deque.pollLast();
  26.         // 结果: [3, 1]
  27.         System.out.println(deque);
  28.         deque.pollFirst();
  29.         // 结果: [1]
  30.         System.out.println(deque);
  31.     }
复制代码
LeetCode之二叉搜刮树

所在链接
  1.     public static void main(String[] args) {
  2.         // 最大最小值
  3.         // 结果: -2147483648
  4.         System.out.println(Integer.MIN_VALUE);
  5.         // 结果: 2147483647
  6.         System.out.println(Integer.MAX_VALUE);
  7.         // 结果: -9223372036854775808
  8.         System.out.println(Long.MIN_VALUE);
  9.         // 结果: 9223372036854775807
  10.         System.out.println(Long.MAX_VALUE);
  11.         // 结果: 1
  12.         System.out.println(Math.min(1, 2));
  13.         // 结果: 2
  14.         System.out.println(Math.max(1, 2));
  15.     }
复制代码
LeetCode之图

所在链接
  1.    public static void main(String[] args) {
  2.         // 图
  3.         int[][] grid = new int[][]{{1, 2, 3}, {4, 5, 6}};
  4.         // 结果: [[1, 2, 3], [4, 5, 6]]
  5.         System.out.println(Arrays.deepToString(grid));
  6.         // 结果: 2
  7.         System.out.println(grid.length);
  8.         // 结果: 3
  9.         System.out.println(grid[0].length);
  10.         // HashMap
  11.         Map<Integer, String> map = new HashMap<>();
  12.         map.put(1, "1");
  13.         map.put(2, "2");
  14.         map.put(3, "3");
  15.         // 结果: true
  16.         System.out.println(map.containsKey(1));
  17.         // 结果: false
  18.         System.out.println(map.containsValue(4));
  19.         // 结果: null;
  20.         System.out.println(map.putIfAbsent(4, "4"));
  21.         for (Map.Entry<Integer, String> item : map.entrySet()) {
  22.             System.out.println(item.getKey());
  23.             System.out.println(item.getValue());
  24.         }
  25.     }
复制代码
LeetCode之图的广度优先搜刮

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. Set
  3.         String[] str = new String[]{"1", "2", "2", "3"};
  4.         List<String> list = Arrays.asList(str);
  5.         // 结果: [1, 2, 2, 3]
  6.         System.out.println(list);
  7.         Set<String> set = new HashSet<>(list);
  8.         // 结果: [1, 2, 3]
  9.         System.out.println(set);
  10.         // 结果: true
  11.         System.out.println(set.contains("1"));
  12.         set.remove("1");
  13.         // 结果: false
  14.         System.out.println(set.contains("1"));
  15.         // 2. 队列,先进先出
  16.         Queue<Integer> queue = new LinkedList<>();
  17.         queue.offer(1);
  18.         queue.offer(2);
  19.         queue.offer(3);
  20.         // 结果: [1, 2, 3]
  21.         System.out.println(queue);
  22.         queue.poll();
  23.         // 结果: [2, 3]
  24.         System.out.println(queue);
  25.         // 结果: 2
  26.         System.out.println(queue.size());
  27.         // 结果: false
  28.         System.out.println(queue.isEmpty());
  29.         // 3. String
  30.         String str1 = "hello";
  31.         StringBuilder sb = new StringBuilder(str1);
  32.         // 结果: hello
  33.         System.out.println(sb);
  34.         sb.setCharAt(1, 'w');
  35.         // 结果: hwllo
  36.         System.out.println(sb.toString());
  37.     }
复制代码
LeetCode之字典树

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. Character
  3.         String str = "abcde";
  4.         char[] charArr = str.toCharArray();
  5.         List<Integer> list = new ArrayList<>();
  6.         for (char item : charArr) {
  7.             int i = item - 'a';
  8.             list.add(i);
  9.         }
  10.         // 结果: [0, 1, 2, 3, 4]
  11.         System.out.println(list);
  12.         // 结果: a
  13.         System.out.println(str.charAt(0));
  14.     }
复制代码
LeetCode之回溯

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. Character
  3.         String str = "hello";
  4.         StringBuilder sb = new StringBuilder(str);
  5.         // 结果: h
  6.         System.out.println(str.charAt(0));
  7.         sb.deleteCharAt(1);
  8.         // 结果: hllo
  9.         System.out.println(sb);
  10.         // 2. List
  11.         List<Integer> list = new ArrayList<>();
  12.         list.add(1);
  13.         list.add(2);
  14.         list.add(3);
  15.         // 结果: [1, 2, 3]
  16.         System.out.println(list);
  17.         list.remove(list.size() - 1);
  18.         // 结果: [1, 2]
  19.         System.out.println(list);
  20.         // 3. Deque
  21.         Deque<Integer> deque = new LinkedList<>();
  22.         deque.addLast(1);
  23.         deque.addLast(2);
  24.         deque.addFirst(0);
  25.         deque.addLast(3);
  26.         // 结果: [0, 1, 2, 3]
  27.         System.out.println(deque);
  28.         deque.removeLast();
  29.         List<Integer> list1 = new ArrayList<>(deque);
  30.         // 结果: [0, 1, 2]
  31.         System.out.println(list1);
  32.         list1.remove(1);
  33.         // 结果: [0, 2]
  34.         System.out.println(list1);
  35.         // 4. StringBuilder
  36.         StringBuilder sb1 = new StringBuilder("hello");
  37.         // 结果: hello
  38.         System.out.println(sb1);
  39.         sb1.deleteCharAt(sb1.length() - 1);
  40.         // 结果: hell
  41.         System.out.println(sb1);
  42.     }
复制代码
LeetCode之分治

所在链接
  1.    static class TreeNode {
  2.         int val;
  3.         TreeNode left;
  4.         TreeNode right;
  5.         public TreeNode() {
  6.         }
  7.         public TreeNode(int val) {
  8.             this.val = val;
  9.         }
  10.         public TreeNode(int val, TreeNode left, TreeNode right) {
  11.             this.val = val;
  12.             this.left = left;
  13.             this.right = right;
  14.         }
  15.     }
  16.     static class ListNode {
  17.         int val;
  18.         ListNode next;
  19.         public ListNode() {}
  20.         public ListNode(int val) {
  21.             this.val = val;
  22.         }
  23.         public ListNode(int val, ListNode next) {
  24.             this.val = val;
  25.             this.next = next;
  26.         }
  27.     }
  28.     public static void main(String[] args) {
  29.         // 1. 中间值计算
  30.         int left = 1;
  31.         int right = 5;
  32.         // 结果: 3 此方式可能会数组越界
  33.         System.out.println((left + right) / 2);
  34.         // 结果: 3 右移1位相当于除以2
  35.         System.out.println((left + right) >> 1);
  36.         // 结果: 3
  37.         System.out.println((right - left) / 2 + left);
  38.         // 2. 排序
  39.         List<String> list = Lists.newArrayList("1", "5", "3", "0");
  40.         // 结果: [1, 5, 3, 0]
  41.         System.out.println(list);
  42.         Collections.sort(list);
  43.         // 结果: [0, 1, 3, 5]
  44.         System.out.println(list);
  45.     }
复制代码
LeetCode之二分查找

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. 中间值计算
  3.         int left = 1;
  4.         int right = 5;
  5.         // 结果: 3 此方式可能会数组越界
  6.         System.out.println((left + right) / 2);
  7.         // 结果: 3 右移1位相当于除以2
  8.         System.out.println((left + right) >> 1);
  9.         // 结果: 3
  10.         System.out.println((right - left) / 2 + left);
  11.         // 2. 二分查找
  12.         int[] nums = new int[]{1, 2, 3, 4};
  13.         int target = 2;
  14.         while (left <= right) {
  15.             int mid = (left + right) / 2;
  16.             if (target <= nums[mid]) {
  17.                 right = mid - 1;
  18.             } else {
  19.                 left = mid + 1;
  20.             }
  21.         }
  22.         // 3. 最大最小值
  23.         int min = Math.min(1, 2);
  24.         int max = Math.max(1, 2);
  25.         // 结果: 1
  26.         System.out.println(min);
  27.         // 结果: 2
  28.         System.out.println(max);
  29.     }
复制代码
LeetCode之堆

所在链接
  1.     public static void main(String[] args) {
  2.         // 1. 优先级队列,会给队列自动排序,头部最小
  3.         PriorityQueue<Integer> queue = new PriorityQueue<>(1);
  4.         queue.offer(5);
  5.         queue.offer(1);
  6.         queue.offer(3);
  7.         queue.offer(2);
  8.         queue.offer(4);
  9.         // 结果: [1, 2, 3, 5, 4]
  10.         System.out.println(queue);
  11.         // 结果: 1
  12.         System.out.println(queue.peek());
  13.         queue.poll();
  14.         // 结果: [2, 4, 3, 5]
  15.         System.out.println(queue);
  16.         // 2. 优先级队列,会给队列自动排序,(降序)头部最大
  17.         PriorityQueue<Integer> queue1 = new PriorityQueue<>(Comparator.reverseOrder());
  18.         queue1.offer(5);
  19.         queue1.offer(1);
  20.         queue1.offer(3);
  21.         queue1.offer(2);
  22.         queue1.offer(4);
  23.         // 结果: [5, 4, 3, 1, 2]
  24.         System.out.println(queue1);
  25.         // 结果: 5
  26.         System.out.println(queue1.peek());
  27.         queue1.poll();
  28.         // 结果: [4, 2, 3, 1]
  29.         System.out.println(queue1);
  30.         // 3. 数组
  31.         PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] + a[1] - b[0] - b[1]);
  32.         pq.offer(new int[]{1, 2});
  33.         pq.offer(new int[]{0, 1});
  34.         pq.offer(new int[]{2, 3});
  35.         List<String> list = new ArrayList<>();
  36.         for (int[] ints : pq) {
  37.             list.add(Arrays.toString(ints));
  38.         }
  39.         // 结果: [[0, 1], [1, 2], [2, 3]]
  40.         System.out.println(list);
  41.         // 4. List
  42.         // 结果: [1, 2, 3]
  43.         System.out.println(Lists.newArrayList("1", "2", "3"));
  44.     }
复制代码
LeetCode之位运算

所在链接
  1.     public static void main(String[] args) {
  2.         // 1、StringBuilder
  3.         StringBuilder sb = new StringBuilder("abc");
  4.         // 结果: cba
  5.         System.out.println(sb.reverse());
  6.         // 结果: 49
  7.         System.out.println('a' - '0');
  8.         // 结果: 50
  9.         System.out.println('b' - '0');
  10.         // 结果: 51
  11.         System.out.println('c' - '0');
  12.         // 结果: 2
  13.         System.out.println('c' - 'a');
  14.         // 2、位操作 取出 3 的最低位
  15.         // 结果: 1
  16.         System.out.println(3 & 1);
  17.         // 3、异或
  18.         // 异或运算的特性是:相同的数字相互抵消
  19.         // 0 与 任何数字异或都等于该数字
  20.         // 结果: 0
  21.         System.out.println( 5 ^ 5);
  22.         // 结果: 5
  23.         System.out.println(0 ^ 5);
  24.     }
复制代码
LeetCode之数学

所在链接
  1.     public static void main(String[] args) {
  2.         // 1、String
  3.         String str = String.valueOf(123);
  4.         StringBuilder sb = new StringBuilder(str);
  5.         System.out.println(sb.reverse().toString());
  6.         // 2、double
  7.         System.out.println(2 / 1.0);
  8.         System.out.println(2 % 1.0);
  9.     }
复制代码
LeetCode之一维动态规划

所在链接
  1.     public static void main(String[] args) {
  2.         // 1、最大最小值
  3.         int min = Math.min(1, 2);
  4.         int max = Math.max(1, 2);
  5.         // 结果: 1
  6.         System.out.println(min);
  7.         // 结果: 2
  8.         System.out.println(max);
  9.         // 2、Set
  10.         Set<String> set = new HashSet<>();
  11.         set.add("1");
  12.         set.add("2");
  13.         // 结果: true
  14.         System.out.println(set.contains("1"));
  15.         // 3、Array
  16.         int[] arr = new int[5];
  17.         // 结果: [0, 0, 0, 0, 0]
  18.         System.out.println(Arrays.toString(arr));
  19.         Arrays.fill(arr, 1);
  20.         // 结果: [1, 1, 1, 1, 1]
  21.         System.out.println(Arrays.toString(arr));
  22.     }
复制代码
LeetCode之多维动态规划

所在链接
  1.     public static void main(String[] args) {
  2.         // 1、CharArray
  3.         String str = "abcde";
  4.         char[] chars = str.toCharArray();
  5.         // 结果: [a, b, c, d, e]
  6.         System.out.println(Arrays.toString(chars));
  7.         // 结果: a
  8.         System.out.println(str.charAt(0));
  9.         // 结果: bcd
  10.         System.out.println(str.substring(1, str.length() - 1));
  11.         // 2、最大最小值
  12.         // 结果: 1
  13.         System.out.println(Math.min(1, 2));
  14.         // 结果: 4
  15.         System.out.println(Math.max(2, 4));
  16.     }
复制代码
LeetCode之多线程

所在链接
  1.     // 1. 基础Thread类
  2.     static class MyThread extends Thread {
  3.         @Override
  4.         public void run() {
  5.             System.out.println("Thread is running: " + Thread.currentThread().getName());
  6.         }
  7.         public static void main(String[] args) {
  8.             MyThread thread1 = new MyThread();
  9.             MyThread thread2 = new MyThread();
  10.             // 启动线程1 结果: Thread is running: Thread-0
  11.             thread1.start();
  12.             // 启动线程2 结果: Thread is running: Thread-1
  13.             thread2.start();
  14.         }
  15.     }
  16.     // 2. 实现Runnable接口
  17.     static class MyRunnable implements Runnable {
  18.         @Override
  19.         public void run() {
  20.             System.out.println("Thread is running: " + Thread.currentThread().getName());
  21.         }
  22.         public static void main(String[] args) {
  23.             Thread thread1 = new Thread(new MyRunnable());
  24.             Thread thread2 = new Thread(new MyRunnable());
  25.             // 使用Lambda表达式简化Runnable的实现
  26.             Thread thread3 = new Thread(() -> System.out.println("Thread is running: " + Thread.currentThread().getName()));
  27.             // 启动线程1 结果: Thread is running: Thread-0
  28.             thread1.start();
  29.             // 启动线程2 结果: Thread is running: Thread-1
  30.             thread2.start();
  31.             // 启动线程3 结果: Thread is running: Thread-2
  32.             thread3.start();
  33.         }
  34.     }
  35.     // 3. 实现Callable接口
  36.     static class MyCallable implements Callable<String> {
  37.         @Override
  38.         public String call() throws Exception {
  39.             System.out.println("Thread is running: " + Thread.currentThread().getName());
  40.             return Thread.currentThread().getName();
  41.         }
  42.         public static void main(String[] args) throws ExecutionException, InterruptedException {
  43.             MyCallable myCallable = new MyCallable();
  44.             // FutureTask实现了RunnableFuture接口,而RunnableFuture接口同时继承了Runnable接口和Future接口
  45.             FutureTask<String> futureTask = new FutureTask<>(myCallable);
  46.             Thread thread = new Thread(futureTask);
  47.             // 启动线程 结果: Thread is running: Thread-0
  48.             thread.start();
  49.             // 结果: Thread-0
  50.             System.out.println(futureTask.get());
  51.         }
  52.     }
  53.    
  54.     // 4. 线程池方式
  55.     public static void main(String[] args) throws ExecutionException, InterruptedException {
  56.         ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4,
  57.                 4,
  58.                 60,
  59.                 TimeUnit.SECONDS,
  60.                 new ArrayBlockingQueue<>(20000),
  61.                 new ThreadPoolExecutor.CallerRunsPolicy());
  62.         Runnable task1 = () -> System.out.println("task1 is running: " + Thread.currentThread().getName());
  63.         Runnable task2 = () -> System.out.println("task2 is running: " + Thread.currentThread().getName());
  64.         Callable<String> task3 = () -> {
  65.             System.out.println("task3 is running: " + Thread.currentThread().getName());
  66.             return Thread.currentThread().getName();
  67.         };
  68.         // Runnable无返回值,异常处理简单;Callable有返回值,异常处理更加灵活,使用submit()提交,返回一个Future对象,用于获取任务的结果
  69.         // 提交任务1 结果: task1 is running: pool-1-thread-1
  70.         threadPoolExecutor.execute(task1);
  71.         // 提交任务2 结果: task2 is running: pool-1-thread-2
  72.         threadPoolExecutor.submit(task2);
  73.         // 提交任务3 结果: task3 is running: pool-1-thread-3
  74.         Future<String> submit = threadPoolExecutor.submit(task3);
  75.         // 结果: pool-1-thread-3
  76.         System.out.println(submit.get());
  77.     }
  78.     /**
  79.      * CountDownLatch 适用于需要等待其他线程完成某些操作后再继续的场景
  80.      * 主线程等待3个工作线程完成后再继续执行
  81.      * 结果
  82.      * <p>
  83.      * Thread-0 is working.
  84.      * Thread-1 is working.
  85.      * Thread-2 is working.
  86.      * Thread-0 finished work.
  87.      * Thread-1 finished work.
  88.      * Thread-2 finished work.
  89.      * Main thread resumes after all workers finished.
  90.      */
  91.     public static void main1(String[] args) throws InterruptedException {
  92.         CountDownLatch countDownLatch = new CountDownLatch(3);
  93.         for (int i = 0; i < 3; i++) {
  94.             new Thread(() -> {
  95.                 System.out.println(Thread.currentThread().getName() + " is working.");
  96.                 // 工作完成,计数减一
  97.                 countDownLatch.countDown();
  98.                 System.out.println(Thread.currentThread().getName() + " finished work.");
  99.             }).start();
  100.         }
  101.         // 等待计数为0
  102.         countDownLatch.await();
  103.         System.out.println("Main thread resumes after all workers finished.");
  104.     }
  105.     /**
  106.      * 限制同时访问共享资源的线程数量
  107.      * <p>
  108.      * 结果
  109.      * Thread-0 is working.
  110.      * Thread-1 is working.
  111.      * Thread-0 finished work.
  112.      * Thread-1 finished work.
  113.      * Thread-2 is working.
  114.      * Thread-3 is working.
  115.      * Thread-2 finished work.
  116.      * Thread-3 finished work.
  117.      * Thread-4 is working.
  118.      * Thread-4 finished work.
  119.      */
  120.     public static void main2(String[] args) {
  121.         // 允许
  122.         Semaphore semaphore = new Semaphore(2);
  123.         for (int i = 0; i < 5; i++) {
  124.             new Thread(() -> {
  125.                 try {
  126.                     // 获取许可(如果当前可用的许可证(计数器值)大于 0,许可证计数减少 1,线程可以继续执行)
  127.                     // 如果没有可用的许可证(计数器值为 0),线程将被阻塞,直到其他线程释放许可证
  128.                     semaphore.acquire();
  129.                     System.out.println(Thread.currentThread().getName() + " is working.");
  130.                     // 模拟工作
  131.                     Thread.sleep(1000);
  132.                     System.out.println(Thread.currentThread().getName() + " finished work.");
  133.                 } catch (Exception e) {
  134.                     e.printStackTrace();
  135.                 } finally {
  136.                     // 释放许可
  137.                     // 许可证计数器增加 1,表示有一个新的许可证可用
  138.                     // 如果有任何被阻塞的线程正在等待许可证,它们会被唤醒,重新尝试获取许可证
  139.                     semaphore.release();
  140.                 }
  141.             }).start();
  142.         }
  143.     }
  144.     /**
  145.      * 多个线程在一处同时执行,所有线程到达后再继续
  146.      * 结果
  147.      * <p>
  148.      * Thread-0 is at the barrier.
  149.      * Thread-1 is at the barrier.
  150.      * Thread-2 is at the barrier.
  151.      * All threads reached the barrier, continuing execution.
  152.      * Thread-2 has crossed the barrier.
  153.      * Thread-1 has crossed the barrier.
  154.      * Thread-0 has crossed the barrier.
  155.      */
  156.     public static void main3(String[] args) {
  157.         // 当所有线程到达时执行
  158.         CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> System.out.println("All threads reached the barrier, continuing execution."));
  159.         for (int i = 0; i < 3; i++) {
  160.             new Thread(() -> {
  161.                 System.out.println(Thread.currentThread().getName() + " is at the barrier.");
  162.                 // 等待其他线程到达
  163.                 try {
  164.                     cyclicBarrier.await();
  165.                 } catch (Exception e) {
  166.                     System.out.println("cyclicBarrier catch error" + e);
  167.                 }
  168.                 System.out.println(Thread.currentThread().getName() + " has crossed the barrier.");
  169.             }).start();
  170.         }
  171.     }
  172.     /**
  173.      * wait()和notify()
  174.      * 结果
  175.      * Produced: 0
  176.      * Consumed: 0
  177.      * Produced: 1
  178.      * Consumed: 1
  179.      * Produced: 2
  180.      * Consumed: 2
  181.      * Produced: 3
  182.      * Consumed: 3
  183.      * Produced: 4
  184.      * Consumed: 4
  185.      */
  186.     private static final Object lock = new Object();
  187.     private static boolean ready = false;
  188.     public static void main4(String[] args) {
  189.         Thread producer = new Thread(() -> {
  190.             synchronized (lock) {
  191.                 for (int i = 0; i < 5; i++) {
  192.                     while (ready) {
  193.                         try {
  194.                             lock.wait();
  195.                         } catch (InterruptedException e) {
  196.                             e.printStackTrace();
  197.                         }
  198.                     }
  199.                     ready = true;
  200.                     System.out.println("Produced: " + i);
  201.                     lock.notifyAll();
  202.                 }
  203.             }
  204.         });
  205.         Thread consumer = new Thread(() -> {
  206.             synchronized (lock) {
  207.                 for (int i = 0; i < 5; i++) {
  208.                     while (!ready) {
  209.                         try {
  210.                             lock.wait();
  211.                         } catch (InterruptedException e) {
  212.                             e.printStackTrace();
  213.                         }
  214.                     }
  215.                     ready = false;
  216.                     System.out.println("Consumed: " + i);
  217.                     lock.notifyAll();
  218.                 }
  219.             }
  220.         });
  221.         producer.start();
  222.         consumer.start();
  223.     }
  224.     private static final Lock lock1 = new ReentrantLock();
  225.     private static final Condition condition = lock1.newCondition();
  226.     /**
  227.      * await()和signal()
  228.      * 结果
  229.      * Produced: 0
  230.      * Consumed: 0
  231.      * Produced: 1
  232.      * Consumed: 1
  233.      * Produced: 2
  234.      * Consumed: 2
  235.      * Produced: 3
  236.      * Consumed: 3
  237.      * Produced: 4
  238.      * Consumed: 4
  239.      */
  240.     public static void main(String[] args) {
  241.         Thread producer = new Thread(() -> {
  242.             lock1.lock();
  243.             try {
  244.                 for (int i = 0; i < 5; i++) {
  245.                     while (ready) {
  246.                         condition.await();
  247.                     }
  248.                     ready = true;
  249.                     System.out.println("Produced: " + i);
  250.                     condition.signalAll();
  251.                 }
  252.             } catch (InterruptedException e) {
  253.                 e.printStackTrace();
  254.             } finally {
  255.                 lock1.unlock();
  256.             }
  257.         });
  258.         Thread consumer = new Thread(() -> {
  259.             lock1.lock();
  260.             try {
  261.                 for (int i = 0; i < 5; i++) {
  262.                     while (!ready) {
  263.                         condition.await();
  264.                     }
  265.                     ready = false;
  266.                     System.out.println("Consumed: " + i);
  267.                     condition.signalAll();
  268.                 }
  269.             } catch (Exception e) {
  270.                 e.printStackTrace();
  271.             } finally {
  272.                 lock1.unlock();
  273.             }
  274.         });
  275.         producer.start();
  276.         consumer.start();
  277.     }
复制代码
 
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表