代码模板
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
}
}
快排模板
private static void quickSort(int[] q, int l , int r) {
// 递归终止条件
if (l >= r) return;
// 取分界点
int x = q[l];
int i = l - 1;
int j = r + 1;
while (i < j) {
while (q[++i] < x);
while (q[--j] > x);
if (i < j) {
int tmp = q[i];
q[i] = q[j];
q[j] = tmp;
}
}
// 递归交换左右两个区间
quickSort(q, l, j);
quickSort(q, j + 1, r);
}
归并排序
public static void mergeSort(int[] q, int l, int r) {
if (l >= r) return;
int mid = l + r >> 1;
// 递归对左右半边处理
mergeSort(q, l, mid);
mergeSort(q, mid + 1, r);
// 排序,归并
int i = l;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= r)
if (q[i] <= q[j]) tmp[k++] = q[i++];
else tmp[k++] = q[j++];
while (i <= mid) tmp[k++] = q[i++];
while (j <= r) tmp[k++] = q[j++];
// 存回原序列中
for (i = l, j = 0; i <= r; i++, j++) q[i] = tmp[j];
}
}
二分查找
索引二分查找
public static void binarySearch(int[] q, int k) {
// 查询k左边界
int l = 0;
int r = q.length - 1;
while (l < r) {
int mid = l + r >> 1;
if (q[mid] >= k) r = mid;
else l = mid + 1;
}
if (q[l] != k) { System.out.println("-1 -1"); return; }
System.out.print("" + l + " ");
// 查询k右边界
l = 0;
r = q.length - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (q[mid] <= k) l = mid;
else r = mid - 1;
}
System.out.println("" + l);
}
值域二分查找
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
double l = -10000;
double r = 10000;
// 满足6位小数精度
while (r - l > 1e-8) {
double mid = (l + r) / 2.0;
if (mid * mid * mid >= n) r = mid;
else l = mid;
}
System.out.println(String.format("%.6f", l));
}
}
大精度相加
public static String add(String a, String b) {
int i = a.length() - 1;
int j = b.length() - 1;
int t = 0;
StringBuilder sb = new StringBuilder();
while (i >=0 || j >= 0 || t != 0) {
if (i >= 0) t += a.charAt(i--) - '0';
if (j >= 0) t += b.charAt(j--) - '0';
sb.append(t % 10);
t /= 10;
}
return sb.reverse().toString();
}
前缀和
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int[] num = new int[n];
for (int i = 0; i < n ; i++) {
num[i] = s.nextInt();
}
// 求前缀和
int[] sum = new int[n + 1];
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1] + num[i - 1];
}
for (int i = 0; i < m; i++) {
int l = s.nextInt();
int r = s.nextInt();
int res = sum[r] - sum[l - 1];
System.out.println(res);
}
}
还会更新码老哥
这是算法基础班的java模板题解嘛?期待更新(*❦ω❦)
是的呢。最近工作有点忙,后面继续补充哈~