Java基础知识总结(持续更新中)

Java基础知识(持续更新)

类型转化:数字、字符串、字符之间相互转化

  1. 数字 <-> 字符串
// 数字转字符串
//  method1
      int number = 5;
      String str = String.valueOf(number);
      
//  method2
      int number = 5;
      Integer itr = number;  //int装箱为对象,再调用对象的toString方法
      String str = itr.toString(); //或者直接 String str = Integer.toString(number);
      
// method3
      int number = 5;
      String str = number + "";
  
// 字符串转数字
      String str = "123";
      int number = Integer.parseInt(str);
  1. 字符串 <-> 字符
// 字符串转字符
// method 1  单个字符
       String str = "123";
       char ch = str.charAt(0); //charAt(index)方法,这里获取到的字符为1
       
// method 2 
       for (int i = 0; i < str.length(); i++) {
            System.out.println(str.substring(i, i + 1));
        }
        
// method 3  字符串转成字符数组
       String str = "123";
       char [] charArray = str.toCharArray();
       
// 单字符转字符串
// method 1
       char ch = '5';
       String str = String.valueOf(ch);

// method 2
       char ch = '5';
       String str = ch + "";
       
// method 3 字符数组转化成字符串 
       String newStr = new String(charArray, 0, charArray.length);
     
  1. 字符 <-> 数字
// 字符转数字
// method 1
        char ch = '5';
        int a = ch - '0';
        
// method 2 ( 字符 -> 字符串 -> 数字 )
                // 先把字符转为字符串,再转换为数字
                char ch = '5';
                String temp = String.valueOf(ch);
                int a = Integer.parseInt(temp);

// 数字转字符 ( 数字 -> 字符串 -> 字符 )
       // 不能直接转换,因此需借助数字转字符串。
       // 首先将数字转为字符串,再获取字符
       int number = 5; //注意这里数字只能是个位数并且不能为负
       String s = Integer.toString(number);
       char ch = s.charAt(0);
  1. 与数组之间的转化
// String -> char[]
String s = "3456789XJQKA2MF";
char [] charArray = s.toCharArray();

// char[] -> String
String s = new String(charArray, 0, charArray.length);

// 将 ch[i] 设为空 ch[i] = '\0'

// List -> Integer
List<Integer> nums
Integer[] arr = nums.toArray(new Integer[0]);

String类

  1. 字符串相减/替换

使用 String 类的 replace() 方法来实现这个功能: replace(“target”,“replacement”)

如果你想将引号添加到字符串中,你可以使用转义字符 \" 来表示双引号。

String str1 = "abcdefg";
String str2 = "bcd";
String result = str1.replace(str2, "");
System.out.println(result);  // 输出: aefg
  1. 字符串连接

使用 String 类的 concat() 方法来实现这个功能: contact(String s)

也可以用StringBuilder类来添加,空间效率更快

 String s = "菜鸟教程";
 s = s.concat("网址:").concat("www.runoob.com");
 System.out.println(s);    //输出 菜鸟教程网址:www.runoob.com
  1. 比较子/字符串是否相同
  • equals() 方法
String str1 = "abc";
String str2 = "123a";
str1.equals(str2);    //输出 false
"abc".equals(str2);    //输出 true
  • equalsIgnoreCase() 方法 --不区分大小写
String str1 = "abc";
String str2 = "ABC";
System.out.println(str1.equalsIgnoreCase(str2));    // 输出 true
  • compareTo() 方法

compareTo() 方法用于按字典顺序比较两个字符串的大小,该比较是基于字符串各个字符的 Unicode 值。

String str1 = "A";
String str2 = "a";
System.out.println(str1.compareTo(str2));    // a - A 输出 32
System.out.println(str2.compareTo(str1));    // A - a 输出 -32
System.out.println(str2.compareTo("a"));    // 相同输出 0
  1. 字符串是否包含

contains() 方法

String str = "abcdef";
boolean statue = srt.contains("bc");    // statue = true;
  1. 获取子字符串
  • substring(int beginIndex)

    1. 这个版本的substring方法从指定的索引位置开始,提取字符串的一部分,一直到字符串的末尾。
  • substring(int beginIndex, int endIndex)

    • 这个版本的substring方法从指定的起始索引位置开始,提取字符串的一部分,直到结束索引之前的位置。

    • public class SubstringExample {
          public static void main(String[] args) {
              String s = "Hello, world!";
              // 第1个substring方法
              // 使用单个索引,提取从索引2开始到末尾的子字符串
              String substring1 = s.substring(2);
              System.out.println("Substring 1: " + substring1); // 输出:llo, world!
              
              // 第2个substring方法
              // 使用两个索引,提取从索引7到索引12之前的子字符串,即 7 - 11 
              String substring2 = s.substring(7, 12);
              System.out.println("Substring 2: " + substring2); // 输出:world
              
              // 提取索引4之前的子字符串(索引4不包括在内)
              String substring3 = s.substring(0, 4);
              System.out.println("Substring 3: " + substring3); // 输出:Hell
          }
      }
      
  1. 查找 字符/串 位置
  • int indexOf(String str)

    1. 这个版本的 indexOf 方法用于查找指定子字符串在字符串中第一次出现的索引位置。
  • int indexOf(String str,int fromIndex):

    • 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

    • public class IndexOfExample {
          public static void main(String[] args) {
              String text = "Hello, world! This is a sample text.";
              // 第1个indexOf方法
              // 查找字符 ',' 第一次出现的索引
              int commaIndex = text.indexOf(',');
              System.out.println( commaIndex); // 输出: 5
      
              // 查找子字符串 "world" 第一次出现的索引
              int worldIndex = text.indexOf("world");
              System.out.println( worldIndex); // 输出: 7
      
              // 查找不存在的字符或子字符串
              int notFoundIndex = text.indexOf("123");
              System.out.println( notFoundIndex); // 输出:-1
              
              // 第二个indexOf方法
              String t = text.indexOf("o",6);
              System.out.println( t); // 输出: 8
          }
      }
      
  1. 进制转化

十进制转化为其他进制

public static boolean check(int base, int num){ // 进制位, 转换数
        int t = num;
        int sum = 0;
        while (t != 0){
            sum += t % base;
            t /= base;
        }
        return num % sum == 0;
    }

System.out.println(n + "的三进制是:" + Integer.toString(n, 3));
System.out.println(n + "的二进制是:" + Integer.toBinaryString(n));
System.out.println(n + "的八进制是:" + Integer.toOctalString(n));
System.out.println(n + "的十六进制是:" + Integer.toHexString(n));

其他进制转为十进制

r进制转10进制方法
radix进制的字符串s转10进制Integer.parseInt((String) s,(int) radix);
    public static void main(String[] args) {
        String a = "1001";
        int s = Integer.parseInt(a, 2);// 二进制转十进制
        System.out.println(s);
    }

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. 大小写变换
s = s.toLowerCase(); //转换成小写
s = s.toUpperCase(); //转换成大写
String 方法

下面是 String 类支持的方法,更多详细,参看 Java String API 文档:

序号方法描述
1char charAt(int index) 返回指定索引处的 char 值。
2int compareTo(Object o) 把这个字符串和另一个对象比较。
3int compareTo(String anotherString) 按字典顺序比较两个字符串。
4int compareToIgnoreCase(String str) 按字典顺序比较两个字符串,不考虑大小写。
5String concat(String str) 将指定字符串连接到此字符串的结尾。
6boolean contentEquals(StringBuffer sb) 当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。
7[static String copyValueOf(char] data) 返回指定数组中表示该字符序列的 String。
8[static String copyValueOf(char] data, int offset, int count) 返回指定数组中表示该字符序列的 String。
9boolean endsWith(String suffix) 测试此字符串是否以指定的后缀结束。
10boolean equals(Object anObject) 将此字符串与指定的对象比较。
11boolean equalsIgnoreCase(String anotherString) 将此 String 与另一个 String 比较,不考虑大小写。
12[byte] getBytes() 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
13[byte] getBytes(String charsetName) 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
14[void getChars(int srcBegin, int srcEnd, char] dst, int dstBegin) 将字符从此字符串复制到目标字符数组。
15int hashCode() 返回此字符串的哈希码。
16int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。
17int indexOf(int ch, int fromIndex) 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
18int indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引。
19int indexOf(String str, int fromIndex) 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
20String intern() 返回字符串对象的规范化表示形式。
21int lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出现处的索引。
22int lastIndexOf(int ch, int fromIndex) 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
23int lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。
24int lastIndexOf(String str, int fromIndex) 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
25int length() 返回此字符串的长度。
26boolean matches(String regex) 告知此字符串是否匹配给定的正则表达式。
27boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。
28boolean regionMatches(int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。
29String replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
30String replaceAll(String regex, String replacement) 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
31String replaceFirst(String regex, String replacement) 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
32[String] split(String regex) 根据给定正则表达式的匹配拆分此字符串。
33[String] split(String regex, int limit) 根据匹配给定的正则表达式来拆分此字符串。
34boolean startsWith(String prefix) 测试此字符串是否以指定的前缀开始。
35boolean startsWith(String prefix, int toffset) 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
36CharSequence subSequence(int beginIndex, int endIndex) 返回一个新的字符序列,它是此序列的一个子序列。
37String substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。
38String substring(int beginIndex, int endIndex) 返回一个新字符串,它是此字符串的一个子字符串。
39[char] toCharArray() 将此字符串转换为一个新的字符数组。
40String toLowerCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
41String toLowerCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
42String toString() 返回此对象本身(它已经是一个字符串!)。
43String toUpperCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
44String toUpperCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
45String trim() 返回字符串的副本,忽略前导空白和尾部空白。
46static String valueOf(primitive data type x) 返回给定data type类型x参数的字符串表示形式。
47contains(CharSequence chars) 判断是否包含指定的字符系列。
48isEmpty() 判断字符串是否为空。

StringBuilder/StringBuffer类

当对字符串进行修改的时候,使用 StringBuffer / StringBuilder 类更方便。和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。方法类似

public class RunoobTest{
    public static void main(String args[]){
        StringBuilder sb = new StringBuilder(10);// 创建对象并设置字符序列长度为 10,也可不设置
        // StringBuilder/StringBuff 常用方法
        // 追加字符 append(String s/ char c)
        sb.append("Runoob..");
        
        // 插入字符 insert(int offset, String s)
        sb.insert(7, "Java");
        
        // 删除字符 delete(int start, int end)
        sb.delete(4,7);
        
        // 替换字符 replace(int start, int end, String str)
        
        // 反转字符 reverse()
        sb.reverse();
        
        // 字符串形式表示 toString()
        sb.toString()
    }
}
StringBuffer 方法

以下是 StringBuffer 类支持的主要方法:

序号方法描述
1public StringBuffer append(String s) 将指定的字符串追加到此字符序列。
2public StringBuffer reverse() 将此字符序列用其反转形式取代。
3public delete(int start, int end) 移除此序列的子字符串中的字符。
4public insert(int offset, int i) 将 int 参数的字符串表示形式插入此序列中。
5insert(int offset, String str) 将 str 参数的字符串插入此序列中。
6replace(int start, int end, String str) 使用给定 String 中的字符替换此序列的子字符串中的字符。

以下列表列出了 StringBuffer 类的其他常用方法:

序号方法描述
1int capacity() 返回当前容量。
2char charAt(int index) 返回此序列中指定索引处的 char 值。
3void ensureCapacity(int minimumCapacity) 确保容量至少等于指定的最小值。
4void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 将字符从此序列复制到目标字符数组 dst。
5int indexOf(String str) 返回第一次出现的指定子字符串在该字符串中的索引。
6int indexOf(String str, int fromIndex) 从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引。
7int lastIndexOf(String str) 返回最右边出现的指定子字符串在此字符串中的索引。
8int lastIndexOf(String str, int fromIndex) 返回 String 对象中子字符串最后出现的位置。
9int length() 返回长度(字符数)。
10void setCharAt(int index, char ch) 将给定索引处的字符设置为 ch。
11void setLength(int newLength) 设置字符序列的长度。
12CharSequence subSequence(int start, int end) 返回一个新的字符序列,该字符序列是此序列的子序列。
13String substring(int start) 返回一个新的 String,它包含此字符序列当前所包含的字符子序列。
14String substring(int start, int end) 返回一个新的 String,它包含此序列当前所包含的字符子序列。
15String toString() 返回此序列中数据的字符串表示形式。

Math类

  1. 对数字开方

Math.sqrt(16) -> 4

  1. 对数字取整数

向上取整:Math.ceil(double a) [n/x] = [(n+x-1)/x] 向下取整:Math.floor(double a) 四舍五入取整:Math.round(double a)

例:

Math.ceil(24.1)–> 25

Math.floor(24.8)–> 24

Math.round(24.1)–> 24

Math.round(24.8)–> 25

import java.text.DecimalFormat;
public class Main {
    public static void main(String[] args) {
        double number1 = 25.00000;
        double number2 = 5432.10;
        //"#.######"指定了保留六位有效数字,小数点后不足6位不补0
        DecimalFormat decimalFormat = new DecimalFormat("#.######");
        
        // 设置最小小数位数为0,不写也可以
        decimalFormat.setMinimumFractionDigits(0); 

        String formattedNumber1 = decimalFormat.format(number1);
        String formattedNumber2 = decimalFormat.format(number2);

        System.out.println(formattedNumber1); // 输出:25
        System.out.println(formattedNumber2); // 输出:5432.1
    }
}
  1. 高精度计算(数大于long)
import java.math.BigDecimal;
public class HighPrecisionExample {
    public static void main(String[] args) {
        // 使用字符串构造BigDecimal以确保精度准确
        BigDecimal num1 = new BigDecimal("123.456");
        BigDecimal num2 = new BigDecimal("789.012");

        // 加法
        BigDecimal sum = num1.add(num2);

        // 减法
        BigDecimal difference = num1.subtract(num2);

        // 乘法
        BigDecimal product = num1.multiply(num2);

        // 除法,指定精度和舍入模式
        BigDecimal quotient = num1.divide(num2, 10, BigDecimal.ROUND_HALF_UP);
        // ROUND_HALF_UP 四舍五入 ROUND_UP(向上取 ROUND_DOWN 向下取
    }
}
Number & Math 类方法

下面的表中列出的是 Number & Math 类常用的一些方法:

序号方法与描述
1xxxValue() 将 Number 对象转换为xxx数据类型的值并返回。
2compareTo() 将number对象与参数比较。
3equals() 判断number对象是否与参数相等。
4valueOf() 返回一个 Number 对象指定的内置数据类型
5toString() 以字符串形式返回值。
6parseInt() 将字符串解析为int类型。
7abs() 返回参数的绝对值。
8ceil() 返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。
9floor() 返回小于等于(<=)给定参数的最大整数 。
10rint() 返回与参数最接近的整数。返回类型为double。
11round() 它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。
12min() 返回两个参数中的最小值。
13max() 返回两个参数中的最大值。
14exp() 返回自然数底数e的参数次方。
15log() 返回参数的自然数底数的对数值。
16pow() 返回第一个参数的第二个参数次方。
17sqrt() 求参数的算术平方根。
18sin() 求指定double类型参数的正弦值。
19cos() 求指定double类型参数的余弦值。
20tan() 求指定double类型参数的正切值。
21asin() 求指定double类型参数的反正弦值。
22acos() 求指定double类型参数的反余弦值。
23atan() 求指定double类型参数的反正切值。
24atan2() 将笛卡尔坐标转换为极坐标,并返回极坐标的角度值。
25toDegrees() 将参数转化为角度。
26toRadians() 将角度转换为弧度。
27random() 返回一个随机数。

Arrays类

  1. 数组创建
//一维数组
    int [] a = new int [10];
// 二维数组
    String[][] s = new String[3][4];
    //或   列可以先不写,后面要创建
    String[][] s = new String[2][];
    s[0] = new String[2];
    s[1] = new String[3];
//定义包含 first 属性的类
class MyObject {
 int first;
 // 构造函数
 public MyObject(int first) {
    this.first = first;
    }
}

public class Main {
 public static void main(String[] args) {
     // 创建一个包含三个 MyObject 对象的数组
     MyObject[] myArray = new MyObject[2];

     // 初始化数组中的每个元素
     myArray[0] = new MyObject(10);
     myArray[1] = new MyObject(20);
     myArray[0].first = 12;

     // 访问数组中的第一个元素的 first 属性
     int value = myArray[0].first;
     System.out.println("Value of first in the first element: " + value);
     // Value of first in the first element: 12
 }
}
  1. For-Each循环

JDK 1.5 引进了一种新的循环类型,被称为 For-Each 循环或者加强型循环,它能在不使用下标的情况下遍历数组。

for(type element: array)
{
    System.out.println(element);
}

double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (double element: myList) {
     System.out.println(element);
}
  1. 数组赋值

一维数组填充

int [] map = new int [5];
Arrays.fill(map,1); // 将 map数组 填充为 1

二维数组填充

int[][] map=new int[4][5];
Arrays.fill(map,-1); // 失败

int[][] map=new int[4][5];
int[] ten=new int[10];
Arrays.fill(ten, -1);
Arrays.fill(map,ten); // 成功
//特别注意:map 的每一项指向的都是同一个一维数组 ten。修改一个会影响其他地址的值 ,
//如:修改 map[0][1] = 100 ,则 map[1][1] ,map[2][1]等都是100.
  1. 数组排序
// 升序
Arrays.sort(int[] a); // 从小到大,升序
Arrays.sort(int[] a, int fromIndex, int toIndex);//对数组部分排序,区间左闭右开

//多维数组
// 先f[0]升序,若f[0]相同,按f[1]降序
Arrays.sort(f, (o1, o2) -> o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0]);//排序

建议使用Collections.sort()方法,比Arrays.sort()效率高

public static void sort(int[] arr) {
        List<Integer> list = new ArrayList<>();
        for (int i : arr) {
            list.add(i);
        }
        Collections.sort(list);
        for (int i = 0; i < arr.length; i++) {
            arr[i] = list.get(i);
        }
    }
// 降序
//首先要注意的是不能用int这个类型了,要用Integer,不能使用基本类型(int,double, char)
//如果是int型需要改成Integer,float要改成Float
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
 
public class Main {
    public static void main(String[] args) {
        Integer[] arr2={1,4,3,6,7,9,11};
        Arrays.sort(arr2, Collections.reverseOrder());
        System.out.println(Arrays.toString(arr2));
    }
}

// 冒泡排序:降序
public static void sort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            // 如果相邻元素逆序,则交换它们
            if (arr[j] < arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}
  1. 数组比较
Arrays.equals() 适用于一维数组的比较。
Arrays.deepEquals() 更适合用于多维数组,特别是当数组中包含其他数组时。

例子:
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean judge = Arrays.equals(arr1, arr2)); // true

int[][] matrix1 = {{1, 2}, {3, 4}};
int[][] matrix2 = {{1, 2}, {3, 4}};
boolean judge =Arrays.deepEquals(matrix1, matrix2); // true
// 方法源代码
public static boolean equals(long[] a, long[] a2) {
    if (a.length != a2.length) return false;
    for (int i = 0; i < a.length; i++) {
        if (a[i] != a2[i])  return false;
    }
    return true;
}
  1. 指定值第一次出现下标

public static int binarySearch(Object[] a, Object key)

用二分查找算法在数组中搜索给定值的对象(Byte,Int,double等)。数组在调用前必须排序好。如果查找值包含在数组中,则返回索引;否则返回 -1

Arrays.binarySearch(数组, 开始, 结束, 值);

Arrays.binarySearch( arr , 0 , 10 , 5 );在下表为 0 - 9 中搜索

public static void main(String[] args) {
    int[] array = {5, 2, 9, 1, 5, 6};

    // 对数组进行排序
    Arrays.sort(array);
    // 要查找的值
    int targetValue = -9;

    // 使用binarySearch查找值的下标
    int index = Arrays.binarySearch(array, targetValue);
    System.out.println(index);
}
  1. 数组转化为List

Arrays.asList()方法

String[] a = {"apple", "banana", "orange", "grape"};
List<String> list = new ArrayList<>(Arrays.asList(a));

// 不支持结构修改(add、remove 操作)
List<String> list = Arrays.asList(a);

Integer类

  1. 校验数据是否为int、double、string类型的方法 instanceof
String sContentValue = "1234567";
boolean bCheckResult = true;
try
{
        Integer iCheckValue = Integer.parseInt(sContentValue);
                                
        if (iCheckValue instanceof Integer == false){
                bCheckResult = false;
        }
}
catch(NumberFormatException e)
{  
        bCheckResult = false;
}

Collection类

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  1. List 集合排序

只有List集合可以使用Collections.sort(List list)进行排序,若为其他类型集合转化为List集合

Collections.sort(List list)方法(升序排序)

Collections.sort(List list, Collections.reverseOrder());有序集合降序排序(降序排序)

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);numbers.add(2);
        numbers.add(8);numbers.add(1);
        
        // 使用Collections.sort()方法升序排序
        Collections.sort(numbers);
        
        // 降序排序
            // 法1:推荐
            Collections.sort(numbers, Collections.reverseOrder());
            // 法2:Lambda 表达式的排序降序排序
            Collections.sort(b, (x,y)->y-x);
            //或
            list.sort((o1, o2) -> o2 - o1);

    }
}
  1. 遍历集合

遍历ArrayList

import java.util.*;
 
public class Test{
 public static void main(String[] args) {
     List<String> list=new ArrayList<String>();
     list.add("Hello");list.add("World");list.add("HAHAHAHA");
     //第一种遍历方法使用 For-Each 遍历 List
     for (String str : list) {            //也可以改写 for(int i=0;i<list.size();i++) 这种形式
        System.out.println(str);
     }
 
     //第二种遍历,把链表变为数组相关的内容进行遍历
     String[] strArray=new String[list.size()];
     list.toArray(strArray);
     for(int i=0;i<strArray.length;i++) //这里也可以改写为  for(String str:strArray) 这种形式
     {
        System.out.println(strArray[i]);
     }
     
    //第三种遍历 使用迭代器进行相关遍历
     
     Iterator<String> ite=list.iterator();
     while(ite.hasNext())//判断下一个元素之后有值
     {
         System.out.println(ite.next());
     }
 }
}

遍历Map

import java.util.*;
 
public class Test{
     public static void main(String[] args) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("1", "value1");map.put("2", "value2");map.put("3", "value3");
      
      //第一种:普遍使用,二次取值
      System.out.println("通过Map.keySet遍历key和value:");
      for (String key : map.keySet()) {
       System.out.println("key= "+ key + " and value= " + map.get(key));
      }
      
      //第二种
      System.out.println("通过Map.entrySet使用iterator遍历key和value:");
      Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
      while (it.hasNext()) {
       Map.Entry<String, String> entry = it.next();
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }
      
      //第三种:推荐,尤其是容量大时
      System.out.println("通过Map.entrySet遍历key和value");
      for (Map.Entry<String, String> entry : map.entrySet()) {
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }
    
      //第四种
      System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
      for (String v : map.values()) {
       System.out.println("value= " + v);
      }
     }
}

ArrayList集合–元素可重复有序

import java.util.ArrayList; // 引入 ArrayList 类
ArrayList<E> objectName =new ArrayList<>();  // 初始化
//例如
ArrayList<String> sites = new ArrayList<String>();
  • E: 泛型数据类型,泛型String Integer Character Boolean等引用数据类型
  • objectName: 对象名。
  1. 排序
List<Integer> numbers = new ArrayList<>();
numbers.add(5);numbers.add(2);
numbers.add(8);numbers.add(1);

// 使用Collections.sort()方法升序排序
Collections.sort(numbers);

// 降序排序
    // 法1:推荐
    Collections.sort(numbers, Collections.reverseOrder());
    // 法2:Lambda 表达式的排序降序排序
    list.sort((o1, o2) -> o2 - o1);
  1. 删除元素
  • remove(int index):删除指定索引处的元素。
List<Integer> numbers = new ArrayList<>();
numbers.remove(3); // 删除下标为3的元素
  • remove(Object o):删除第一次出现的指定元素。
List<Integer> numbers = new ArrayList<>();
Integer a = 3;
numbers.remove(a);// 删除第一次出现的3

List<String> list = new ArrayList<>();
list.remove("abc");// 删除字符串abc
  • boolean removeAll(Collection<?> c):是否删除另一个集合所有元素
public class RemoveAllExample {
    public static void main(String[] args) {
        // 创建一个ArrayList
        ArrayList<String> list1 = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "grape"));

        // 创建另一个ArrayList,包含要移除的元素
        List<String> elementsToRemove = Arrays.asList("banana", "grape");

        // 使用removeAll移除包含在elementsToRemove中的元素
        boolean result = list1.removeAll(elementsToRemove);

        if (result) {
            System.out.println("移除成功,剩余的元素:" + list1);
        } else {
            System.out.println("列表未发生改变,没有移除任何元素。");
        }
    }
}
常用方法
ArrayList集合常用方法
方法描述
add()将元素插入到指定位置的 arraylist 中
addAll(Collection c)将一个集合所有元素添加到另一个集合
clear()删除 arraylist 中的所有元素
clone()复制一份 arraylist
contains(Object obj)判断元素是否在 arraylist
get(int index)通过索引值获取 arraylist 中的元素
indexOf()返回 arraylist 中元素的第一次出现的索引值
removeAll()删除存在于指定集合中的 arraylist 里的所有元素
remove()删除 arraylist 里的单个元素
size()返回 arraylist 里元素数量
isEmpty()判断 arraylist 是否为空
subList()截取部分 arraylist 的元素
set()替换 arraylist 中指定索引的元素
sort()对 arraylist 元素进行排序
toArray()将 arraylist 转换为数组
toString()将 arraylist 转换为字符串
ArrayList 常用方法
添加元素:
add(E element): 在列表末尾添加一个元素。
add(int index, E element): 在指定索引位置插入一个元素。

获取元素:
get(int index): 获取指定索引位置的元素。

修改元素:
set(int index, E element): 修改指定索引位置的元素。

删除元素:
remove(int index): 删除指定索引位置的元素。
remove(Object obj): 删除第一个出现的指定元素。
// 如 remove(Integer.valueOf(30);// 
clear(): 清空列表中的所有元素。

查找元素:
indexOf(Object obj): 返回指定元素第一次出现的索引,如果不存在则返回 -1。
lastIndexOf(Object obj): 返回指定元素最后一次出现的索引,如果不存在则返回 -1。
contains(Object obj): 判断列表是否包含指定元素。

获得集合大小:
size(): 返回列表中元素的数量。

获得子列表:
subList(int fromIndex, int toIndex): 返回从 fromIndex 到 toIndex 之间的子列表。

isEmpty(): 判断列表是否为空。

数组转换:
toArray(): 将列表转换为数组。
//例如
String[] arr = new String[sites.size()];
sites.toArray(arr);

toString():将Arraylist对象转换为字符串。

HashSet集合–元素不可重复乱序

import java.util.HashSet; // 引入 HashSet 类
//下面两种形式都可以
HashSet<E> sites = new HashSet<E>();
Set<E> set = new HashSet<>();
// 例如:
HashSet<String> sites = new HashSet<String>();
Set<Character> set = new HashSet<>();
获取HashSet元素
// 通过迭代器获取元素
    Iterator<String> iterator = linkedHashSet.iterator();
    while (iterator.hasNext()) {
        String element = iterator.next();
        System.out.println(element);
    }

// 或者将 LinkedHashSet 转换为数组
    String[] array = linkedHashSet.toArray(new String[0]);
    for (String element : array) {
        System.out.println(element);
    }

HashSet 常用方法同 ArrayList 一样,无get()方法

详细参考–菜鸟教程Java HashSet,如下

https://www.runoob.com/java/java-hashset.html

HashSet 按插入顺序排列

HashSet存储元素,HashSet不保证元素的顺序,它是基于哈希表实现的,元素的存储顺序与它们的哈希码有关,而哈希码与元素的插入顺序无关。

如果你希望输出的元素按照插入的顺序进行排列,你可以考虑使用LinkedHashSetLinkedHashSetHashSet的一个子类,它保留了元素的插入顺序。只需稍微修改你的代码,将HashSet替换为LinkedHashSet

如: Set set = new LinkedHashSet<>();

Map类

// 引入 HashMap 类      
import java.util.HashMap;
public class RunoobTest {
    public static void main(String[] args) {
        // 创建 HashMap 对象 Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // 添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        System.out.println(Sites);
    }
}

HashMap 常用方法:

方法描述
clear()删除 hashMap 中的所有键/值对
clone()复制一份 hashMap
isEmpty()判断 hashMap 是否为空
size()计算 hashMap 中键/值对的数量
put()将键/值对添加到 hashMap 中
putAll()将所有键/值对添加到 hashMap 中
putIfAbsent()如果 hashMap 中不存在指定的键,则将指定的键/值对插入到 hashMap 中。
remove()删除 hashMap 中指定键 key 的映射关系
containsKey()检查 hashMap 中是否存在指定的 key 对应的映射关系。
containsValue()检查 hashMap 中是否存在指定的 value 对应的映射关系。
replace()替换 hashMap 中是指定的 key 对应的 value。
replaceAll()将 hashMap 中的所有映射关系替换成给定的函数所执行的结果。
get()获取指定 key 对应对 value
getOrDefault()获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值
forEach()对 hashMap 中的每个映射执行指定的操作。
entrySet()返回 hashMap 中所有映射项的集合集合视图。
keySet()返回 hashMap 中所有 key 组成的集合视图。
values()返回 hashMap 中存在的所有 value 值。
merge()添加键值对到 hashMap 中
compute()对 hashMap 中指定 key 的值进行重新计算
computeIfAbsent()对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hasMap 中
computeIfPresent()对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中。

队列

PriorityQueue 是 Java 中的一个优先队列实现,通过默认情况下是一个小顶堆(元素按升序排列)来实现。如果你希望使用大顶堆(元素按降序排列),你可以通过提供一个 Collections.reverseOrder() 的比较器来实现。以下是用中文描述的代码:

import java.util.Collections;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        // 创建一个大顶堆优先队列
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

        // 添加元素到优先队列
        pq.add(3);
        pq.add(1);
        pq.add(4);
        pq.add(1);
        pq.add(5);

        // 弹出并打印堆顶元素
        while (!pq.isEmpty()) {
            System.out.println(pq.poll());
        }
    }
}

IO流

BufferedReader的使用方法
import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException {
        //创建BufferedReader对象,从键盘读入
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));       
        String str = br.readLine();  //读取一行字符串,br.readLine()读取的为字符串类型
        int n = br.read(); // 读取一个字符,返回对应 ASCII 的值
        int a = Integer.parseInt(str);  //将字符转化为整型
        br.ready();// 判断是否还有下一个,返回类型 boolean
        String[] temp=br.readLine().split(" ");//读取一行数据并用空格分隔,存入字符串数组
    }
}

        // 或
        String str1 = null ;        // 接收输入内容
        try{
            str1 = br.readLine() ;        // 只能读取一行数据
        }catch(IOException e){
            e.printStackTrace() ;        // 输出信息
        }
import java.io.*;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        // 使用空格作为分隔符创建StringTokenizer对象
        StringTokenizer st = new StringTokenizer(s);
        
        // 获得字符串数量
        int n = st.countTokens();
        System.out.println(n);
        
        // 遍历并打印每个标记
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            System.out.println(token);
        }
    }
}
Scanner的使用方法
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);//创建Scanner类对象,从键盘读入数据
        int temp3 = sc.nextInt();
        double temp4 = sc.nextDouble();
        boolean temp5 = sc.nextBoolean();// true / false
        String temp2 = sc.next();//读取字符直到判断输入结束
        String temp1 = sc.nextLine();//读取下一行数据
        long temp = sc.hasNextLong();
        boolean temp = sc.hasNext(String str);//输入的字符与str比较,返回true/false
        sc.hasNext();// 判断是否还有下一个,返回类型 boolean
        sc.hasNextLine();// 判断是否还有下一行是,返回类型 boolean
        String [] s = sc.nextLine().split(" ");
        sc.useDelimiter(" ");//若以空格分隔字符串,需要读取空格才能继续读取
        //或者使用一个空的sc.nextLine()跳过空格 PS:此方法可以设置其他分隔符
        
    }
}

基础知识

  1. ASCII码

在这里插入图片描述

在这里插入图片描述

  1. 位运算符
  • 按位与(&):对应位上的两个二进制数都为1时,结果为1,否则为0。
result = a & b;
  • 按位或(|):对应位上的两个二进制数只要有一个为1时,结果为1,否则为0。
result = a | b;
  • 按位异或(^):对应位上的两个二进制数不相同时,结果为1,相同时结果为0。
result = a ^ b;
  • 按位取反(~):对二进制数的每一位取反,0变为1,1变为0。
result = ~a;
  • 左移(<<):将二进制数向左移动指定的位数,右侧用0填充。
result = a << n;
  • 右移(>>):将二进制数向右移动指定的位数,左侧用符号位填充(对于有符号整数)。
result = a >> n;
  1. 数据类型及范围

获取某类型最大值 MAX_VALUE,例如:int a = Integer.MAX_VALUE

  • 整数类型:

    • byte: 8位,1字节,范围为 -128 到 127 = 2^7-1

    • short: 16位,2字节,范围为 -32768 到 32767 = 2^15-1

    • int: 32位,4字节,范围为 -2147483648 到 2147483647 = 2^31-1 = 2*10^10

    • long: 64位,16字节,范围为 -9223372036854775808

      到9223372036854775807 = 2^63-1 = 9 *10^19

      超过int范围,后面+L 如:long b = 10000000000L

  • 浮点数类型:

    • float: 32位,4字节,范围为约 ±3.4E38
    • double: 64位,64字节,范围为约 ±1.7E308
  • 字符类型:

    • char: 16位,2字节范围为 0 到 65535。表示Unicode字符。
  • 布尔类型:

    • boolean:一般认为1字节 只有两个可能值,truefalse
  1. 单位换算
  • bit(比特) < byte(字节) < kb < mb < gb < tb < pb

    1 byte = 8 bit 1 kb = 1024 byte 1mb =1024 kb

    1 gb = 1024 mb 1 tb = 1024 gb 1 pb = 1024 tb

  • 1s = 1000 ms

  1. 输出格式:对齐方式和宽度控制
// 每个数字占5个位置,右对齐(从最右边输出,在前面补空格)
System.out.printf("%5d",i);   

// 每个数字占5个位置,左对齐(从最左边输出,后面补齐空格)
System.out.printf("%-5d",i);

// 输出小数控制
// 说明:%f默认保留6位,.后面的表示的是小数四舍五入保留的位数
System.out.printf("%.2f",3.1415926);   //小数点后保留2位,即 3.14

// 输出类型 printf 
 short -- %hd
 long  -- %ld
 long long -- %lld
 boolean -- %b

// 输出 %
System.out.printf("%.2f%%",81.82);   //将%输在小数后面,即 81.82% 

// 例子
//六位整数+一位小数点+三位小数=_314315.142(右对齐,左边补一个空格)
System.out.printf("%11.3f\n",314315.1415926);  
System.out.printf("%10.3f\n",314315.1415926);  //6+1+3=10 正好=314315.142
System.out.printf("%11.4f\n",314315.1415926);  //6+1+4=11 正好=314315.1426
System.out.printf("%8.3f\n",314315.1415926);   //6+1+3>8 正常输出=314315.142
System.out.printf("%14.3f\n",314315.1415926);  //6+1+3=14-4 补四个空格=_ _ _ _314315.142

在这里插入图片描述

double p = 0.235987565146
// 四舍五入保留4位小数,后面又0省略 如 p = 230.1 -> 230.1
DecimalFormat form=new DecimalFormat("0.####");
System.out.println(form.format(p));//(0.2360后面的0省略)  0.236 

其他零碎知识点

  1. 正则表达式

str.replaceAll(“6{10,}”, “27”).replaceAll(“6{4,}”, “9”)

// 6出现10次及以上替换为27,出现四次及以上替换为9

  1. 转义字符
        // 换行
        System.out.println("Hello\nWorld");  
//Hello
//World

        // 制表符
        System.out.println("Hello\tWorld");
//Hello        World

        // 退格
        System.out.println("Hello\bWorld");
//HelloWorld

        // 回车
        System.out.println("Hello\rWorld");
        //Hello
//World

        // 单引号和双引号
        System.out.println("She said: \"Hello, World!\"");
        System.out.println("It's a sunny day.");
//She said: "Hello, World!"
//It's a sunny day.

        // 反斜杠自身
        System.out.println("This is a backslash: \\");
 //This is a backslash: \
 
 // 在正则表达式中,需要使用两个反斜杠来转义一些特殊字符。
 // 例如,正则表达式中的 \( 表示 (   而 \\( 表示 \(
 // replaceAll 方法使用正则表达式来替换字符串中的匹配项
        String commend = "(al)G(al)()()G";
        String s = command.replaceAll("\\(\\)","o").replaceAll("\\(al\\)","al");
        System.out.println(s);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/380693.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

vue3 之 通用组件统一注册全局

components/index.js // 把components中的所组件都进行全局化注册 // 通过插件的方式 import ImageView from ./ImageView/index.vue import Sku from ./XtxSku/index.vue export const componentPlugin {install (app) {// app.component(组件名字&#xff0c;组件配置对象)…

moduleID的使用

整个平台上有很多相同的功能&#xff0c;但是需要不同的内容。例如各个模块自己的首页上有滚动新闻、有友好链接等等。为了公用这些功能&#xff0c;平台引入了moduleID的解决方案。 在前端的配置文件中&#xff0c;配置了模块号&#xff1a; 前端页面请求滚动新闻时&#xff0…

一款VMP内存DUMP及IAT修复工具

前言 加壳是恶意软件常用的技巧之一&#xff0c;随着黑客组织技术的不断成熟&#xff0c;越来越多的恶意软件家族都开始使用更高级的加壳方式&#xff0c;以逃避各种安全软件的检测&#xff0c;还有些恶意软件在代码中会使用各种多态变形、加密混淆、反调试、反反分析等技巧&a…

基于JAVA的教学资源共享平台 开源项目

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 数据中心模块2.2 课程档案模块2.3 课程资源模块2.4 课程作业模块2.5 课程评价模块 三、系统设计3.1 用例设计3.2 类图设计3.3 数据库设计3.3.1 课程档案表3.3.2 课程资源表3.3.3 课程作业表3.3.4 课程评价表 四、系统展…

单片机学习笔记---DS1302时钟

上一节我们讲了DS1302的工作原理&#xff0c;这一节我们开始代码演示。 新创建一个工程写上框架 我们需要LCD1602进行显示&#xff0c;所以我们要将LCD1602调试工具那一节的LCD1602的模块化代码给添加进来 然后我们开始创建一个DS1302.c和DS1302.h 根据原理图&#xff0c;为了…

005集——shp格式数据转换乱码问题——arcgis

shp数据格式与其他数据格式转换过程中会遇到乱码等问题&#xff0c;原因如下&#xff1a; 在Shapefile头文件&#xff08;dBase Header&#xff09;中&#xff0c;一般会包含字符编码信息&#xff0c;这个信息称为 LDID &#xff08; Language Driver ID&#xff09;。在使用ar…

博主:今日无更

今天放个假&#xff0c;不更新文章 &#xff08;占位符&#xff09;

龙芯开启ssh服务——使用Putty连接

本文采用龙芯3A6000处理器&#xff0c;Loongnix操作系统。 为了能使用其他电脑远程操控龙芯电脑&#xff0c;需要打开loongnix的ssh服务&#xff0c;并在其他电脑里使用putty连接loongnix。 1 修改ssh配置文件 命令行输入&#xff1a; sudo vim /etc/ssh/sshd_config按下i插…

防疫物资管理新篇章:Java+SpringBoot实战

✍✍计算机编程指导师 ⭐⭐个人介绍&#xff1a;自己非常喜欢研究技术问题&#xff01;专业做Java、Python、微信小程序、安卓、大数据、爬虫、Golang、大屏等实战项目。 ⛽⛽实战项目&#xff1a;有源码或者技术上的问题欢迎在评论区一起讨论交流&#xff01; ⚡⚡ Java实战 |…

问题:A注册会计师必须在期中实施实质性程序的情形是()。 #学习方法#其他

问题&#xff1a;A注册会计师必须在期中实施实质性程序的情形是&#xff08;&#xff09;。 A&#xff0e;甲公司整体控制环境不佳 B&#xff0e;将期中实质性程序所获证据与期末数据进行比较 C&#xff0e;评估的认定层次重大错报风险很高 D&#xff0e;没有把握通过在期中…

Sklearn、TensorFlow 与 Keras 机器学习实用指南第三版(七)

原文&#xff1a;Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 第十六章&#xff1a;使用 RNN 和注意力进行自然语言处理 当艾伦图灵在 1950 年想象他著名的Turing 测试时&#xff0c;他提出了…

leetcode(双指针)283.移动零(C++详细题解)DAY3

文章目录 1.题目示例提示 2.解答思路3.实现代码结果 4.总结 1.题目 给定一个数组 nums&#xff0c;编写一个函数将所有 0 移动到数组的末尾&#xff0c;同时保持非零元素的相对顺序。 请注意 &#xff0c;必须在不复制数组的情况下原地对数组进行操作。 示例 示例 1: 输入…

C语言每日一题(52)单值二叉树

力扣网 965 单值二叉树 题目描述 如果二叉树每个节点都具有相同的值&#xff0c;那么该二叉树就是单值二叉树。 只有给定的树是单值二叉树时&#xff0c;才返回 true&#xff1b;否则返回 false。 示例 1&#xff1a; 输入&#xff1a;[1,1,1,1,1,null,1] 输出&#xff1a;t…

MySQL数据库⑦_复合查询+内外链接(多表/子查询)

目录 1. 回顾基本查询 2. 多表查询 2.1 笛卡尔积初步过滤 3. 自连接 4. 子查询 4.1 单行子查询 4.2 多行子查询 4.2 多列子查询 4.2 from子句中使用子查询 5. 合并查询 6. 内外链接 6.1 内连接 6.2 左外链接 6.2 右外连接 本篇完。 1. 回顾基本查询 先回顾一下…

ctfshow-web11~20-WP

web11 根据提示,查询对ctfshow域名进行dns查询,查看TXT记录 阿里云查询链接:阿里云网站运维检测平台 获取flag成功 web12 根据题目提示,我们访问robots.txt,获取到后台地址 然后我们访问一下后台

Linux线程 分离和同步与互斥 条件变量

Linux线程 分离和同步与互斥 条件变量 1. 分离线程2. 线程互斥与互斥量3. 线程同步与竞态条件4. pthread库与条件变量5. 生产者-消费者 1. 分离线程 什么是线程分离&#xff1f; 线程分离是指线程在结束时&#xff0c;操作系统会自动回收其资源&#xff0c;而无需其他线程显式地…

一文带你读懂Python中的pickle模块

pickle模块&#xff1a; 属于python专有的模块&#xff0c;用法&#xff0c;功能与json类似。 常用方法&#xff1a; dump(obj,fp)&#xff1a;将对象以字符串的形式写入文件中。 load(fp)&#xff1a;将数据从文件中读出&#xff0c;并返回&#xff08;需要变量接收&#…

幻兽帕鲁(Palworld)允许自建私服,它是怎么挣钱的呢?

最近爆火的网游幻兽帕鲁由于官方准备不足导致服务拥堵&#xff0c;游戏公司没有单纯的自建服务器扩容&#xff0c;而是开放了服务器安装包&#xff0c;让玩家自搭私服。玩家自搭私服&#xff0c;游戏公司还怎么挣钱&#xff1f; 幻兽帕鲁的财务模式在允许用户托管服务器的同时…

Low 级别反射型 XSS 攻击演示(附链接)

环境准备 如何搭建 DVWA 靶场保姆级教程&#xff08;附链接&#xff09;https://eclecticism.blog.csdn.net/article/details/135834194?spm1001.2014.3001.5502 测试 打开 DVWA 靶场并登录&#xff0c;找到反射型 XSS 页面&#xff08;笔者这里是 Low 级别&#xff09; 先…

C++算法之双指针、BFS和图论

一、双指针 1.AcWing 1238.日志统计 分析思路 前一区间和后一区间有大部分是存在重复的 我们要做的就是利用这部分 来缩短我们查询的时间 并且在使用双指针时要注意对所有的博客记录按时间从小到大先排好顺序 因为在有序的区间内才能使用双指针记录两个区间相差 相当于把一个…