Merge pull request #970 from cccdev/master

添加 时间复杂度测试程序、链表类 Java版本
This commit is contained in:
程序员Carl
2022-01-03 15:48:50 +08:00
committed by GitHub
3 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,5 @@
在面试中,我们常常会遇到面试官让我们用某种编程语言做题,并要求能够在本地编译运行。
这种模式也被称做ACM模式。
本文将介绍如何用Java处理输入输出。

View File

@ -206,7 +206,62 @@ int main() {
}
}
```
Java版本
```Java
import java.util.Scanner;
public class TimeComplexity {
// o(n)
public static void function1(long n) {
System.out.println("o(n)算法");
long k = 0;
for (long i = 0; i < n; i++) {
k++;
}
}
// o(n^2)
public static void function2(long n) {
System.out.println("o(n^2)算法");
long k = 0;
for (long i = 0; i < n; i++) {
for (long j = 0; j < n; j++) {
k++;
}
}
}
// o(nlogn)
public static void function3(long n) {
System.out.println("o(nlogn)算法");
long k = 0;
for (long i = 0; i < n; i++) {
for (long j = 1; j < n; j = j * 2) { // 注意这里j=1
k++;
}
}
}
public static void main(String[] args) {
while(true) {
Scanner in = new Scanner(System.in);
System.out.print("输入n: ");
int n = in.nextInt();
long startTime = System.currentTimeMillis();
function1(n);
// function2(n);
// function3(n);
long endTime = System.currentTimeMillis();
long costTime = endTime - startTime;
System.out.println("算法耗时 == " + costTime + "ms");
}
}
}
```
# 总结

View File

@ -143,7 +143,30 @@ head->val = 5;
Java
```java
public class ListNode {
// 结点的值
int val;
// 下一个结点
ListNode next;
// 节点的构造函数(无参)
public ListNode() {
}
// 节点的构造函数(有一个参数)
public ListNode(int val) {
this.val = val;
}
// 节点的构造函数(有两个参数)
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
```
Python