Java刷题技巧
数组相关操作
常见
1 2 3 4 5 6 7
| int arr[] = new int[size], n = arr.length;
Arrays.equals(T[], T[]); System.arraycopy(src, 0, dst, 0, len); Arrays.copyOf(src, len); Arrays.copyOfRange(src, from, to); cnt[nxt] = cnt[cur].clone();
|
1 2 3 4 5
| Arrays.sort(T[], Comparator); int arr[][] = {{1, 3}, {3, 1}}; Arrays.sort(arr, (a,b)->b[1]-a[1]); int arr2[] = {1,3,2}; Arrays.sort(arr2, (a,b)->b-a);
|
1 2 3 4 5
| Arrays.fill(arr, 0); private List<Integer>[] g; Arrays.setAll(g, i -> new ArrayList<>());
System.out.println(Arrays.toString(num));
|
翻转
1 2 3 4 5 6 7 8
| int intArr[] = new int[]{1, 2, 3}; int[] reverse1 = IntStream.range(0, intArr.length).map(i -> intArr[intArr.length - 1 - i]).toArray(); Integer integerArr[] = new Integer[]{1, 2, 3}; int[] reverse2 = IntStream.range(0, integerArr.length).map(i -> integerArr[integerArr.length - 1 - i]).toArray();
Collections.reverse(Arrays.asList(integerArr)); Collections.reverse(Arrays.asList(intArr));
|
Array和List互相转换
1 2 3 4 5 6 7 8
| Arrays.asList(new Integer[]{1, 2, 3});
int nums = new int[]{1, 2, 3}; List<Integer> list = Arrays.stream(nums).mapToObj(i -> Integer.valueOf(i)).collect(Collectors.toList());
Set<Integer> set = Arrays.stream(nums2).mapToObj(i -> Integer.valueOf(i)).collect(Collectors.toSet());
|
1 2 3 4 5 6 7 8 9 10
| List<Integer> List = new ArrayList<>();
list.toArray(new Integer[n]);
int[] nums = l.stream().mapToInt(i -> i).toArray();
List<int[]> arrList = new ArrayList<>();
arrList.toArray(new int[n][2]); arrList.toArray(new int[0][2]);
|
1 2 3 4 5 6
| Stream s = Arrays.stream(new Person[2]); Object[] array = s.toArray(); Stream s2 = Arrays.stream(new int[2][2]); Object[] array2 = s2.toArray(); IntStream s3 = Arrays.stream(new int[2]); Object[] array3 = s3.toArray();
|
集合
List
1 2 3 4 5 6
| List<Integer> index = Arrays.asList(6, 6, 2, 3); list.sort(Comparator); Collections.sort(list, (a,b)->a-b); list.equals(); Collections.reverse(list); Collections.shuffle(list);
|
Deque
graph LR
push/pop & poll/peek/addFirst --head--- deque <-- tail <--- offer/addLast
Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| for (int i = 0; i < arr.length; i++) { map.computeIfAbsent(arr[i], key -> new ArrayList<>()).add(i); }
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {} for (int key : map.keySet()) {}
map.merge(key, 1, Integer::sum);
|
有序集合
PriorityQueue
1 2 3 4
| PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->a[0]-b[0]); pq.poll(); pq.peek(); pq.offer();
|
TreeSet/TreeMap
1 2 3 4 5 6 7 8
| TreeSet<Integer> set = new TreeSet<>();
Integer ceiling = set.ceiling(arr[x]), floor = set.floor(arr[x]);
Integer higher = treeSet.higher(tg), lower = treeSet.lower(tg);
set.pollFirst(); set.pollLast(); set.first(); set.last();
|
1 2 3 4 5 6
| treeMap.floorKey(k);
treeMap.floorEntry(k);
treeMap.firstKey(); treeMap.lastKey();
|
数字操作
保留小数
BigDecimal::setScale(int newScale, RoundingMode roundingMode)
1 2 3
| BigDecimal bd = new BigDecimal(ans); bd = bd.setScale(2, RoundingMode.HALF_UP); System.out.println(bd);
|
1 2
| DecimalFormat df = new DecimalFormat("0.00"); return df.format(value);
|
1
| String.format("%.2f", value).toString();
|
大数
BigInteger
1 2 3 4 5
| String res = new BigInteger("2...").subtract(new BigInteger("1")).toString(); add(); subtract(); multiply(); divide(); BigInteger f = BigInteger.ONE; f.shiftLeft(v); f.or(v); f.and(v); f.bitLength();
|
进制转换
1 2 3 4 5
| Integer.valueOf("2a", 16); Integer.toString(int i, int radix); Integer.toBinaryString(int i) Integer.toOctalString(int i) Integer.toHexString(int i)
|
位操作
1 2 3 4 5 6
| int i = 41; Integer.bitCount(i); Integer.highestOneBit(i); Integer.lowestOneBit(i); Integer.numberOfLeadingZeros(i); Integer.numberOfTrailingZeros(i);
|
Bitset
Java util自带BitSet,当然也可以手写,更快
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Bitset { private static final int W = Long.SIZE;
private final long[] bits;
Bitset(int n) { bits = new long[(n + W - 1) / W]; }
void set(int p) { bits[p / W] |= 1L << (p % W); }
boolean has(int p) { return (bits[p / W] & (1L << (p % W))) != 0; }
void or(Bitset other) { for (int i = 0; i < bits.length; i++) { bits[i] |= other.bits[i]; } }
int count() { int c = 0; for (long x : bits) { c += Long.bitCount(x); } return c; } }
|
字符串操作
格式化字符串
1 2
| Pair<Double, Integer> pair = pq.poll(); String s = String.format("%d %.6f\n", pair.getValue(), pair.getKey());
|
字符串转IntStream流
1
| IntStream stream = s.chars();
|
字符串替换
1
| text = text.replaceAll(old, new);
|
StringBuilder
1 2 3 4
| StringBuilder res = new StringBuilder(); res.append(c); res.toString()
|
repeat
1
| String t = "0".repeat(n) + s;
|
字符串拼接 join
1 2
| String splits[] = date.split("-"); return String.join("-", splits);
|
misc
1 2 3
| int diff = a - b; return Integer.compare(diff, 0);
|
1 2
| int nums[] = Arrays.stream(rewardValues).distinct().sorted().toArray(); int nums[] = Arrays.stream(rewardValues).toArray();
|
语法
类似goto
1 2 3 4 5 6 7 8 9 10
| outer: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { break outer; } System.out.println("i = " + i + ", j = " + j); } }
|
在上述示例中,如果 i * j > 6,则会跳出外层循环。
char的for循环
1
| for (char i = 'a'; i <= c; i++)
|
静态初始化list
1 2 3 4 5 6 7 8 9 10 11 12 13
| private static ArrayList<Integer> list = new ArrayList<>() { { boolean[] flag = new boolean[1000000]; for (int i = 2; i < 1000000; i++) { if (!flag[i]) { add(i); for (int j = 2 * i; j < 1000000; j += i) { flag[j] = true; } } } } };
|