auto commit
This commit is contained in:
parent
d8c6cfb89e
commit
5ddb1746c8
45
notes/算法.md
45
notes/算法.md
|
@ -67,8 +67,15 @@ N<sup>3</sup>/6-N<sup>2</sup>/2+N/3 的增长数量级为 O(N<sup>3</sup>)。增
|
|||
ThreeSum 用于统计一个数组中和为 0 的三元组数量。
|
||||
|
||||
```java
|
||||
public class ThreeSum {
|
||||
public static int count(int[] nums) {
|
||||
public interface ThreeSum {
|
||||
int count(int[] nums);
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class ThreeSumSlow implements ThreeSum {
|
||||
@Override
|
||||
public int count(int[] nums) {
|
||||
int N = nums.length;
|
||||
int cnt = 0;
|
||||
for (int i = 0; i < N; i++)
|
||||
|
@ -76,7 +83,6 @@ public class ThreeSum {
|
|||
for (int k = j + 1; k < N; k++)
|
||||
if (nums[i] + nums[j] + nums[k] == 0)
|
||||
cnt++;
|
||||
|
||||
return cnt;
|
||||
}
|
||||
}
|
||||
|
@ -112,19 +118,21 @@ public class ThreeSumFast {
|
|||
```
|
||||
|
||||
```java
|
||||
public class BinarySearch {
|
||||
public static int search(int[] nums, int target) {
|
||||
int l = 0, h = nums.length - 1;
|
||||
while (l <= h) {
|
||||
int m = l + (h - l) / 2;
|
||||
if (target == nums[m])
|
||||
return m;
|
||||
else if (target > nums[m])
|
||||
l = m + 1;
|
||||
else
|
||||
h = m - 1;
|
||||
}
|
||||
return -1;
|
||||
public class ThreeSumFast implements ThreeSum {
|
||||
@Override
|
||||
public int count(int[] nums) {
|
||||
Arrays.sort(nums);
|
||||
int N = nums.length;
|
||||
int cnt = 0;
|
||||
for (int i = 0; i < N; i++)
|
||||
for (int j = i + 1; j < N; j++) {
|
||||
int target = -nums[i] - nums[j];
|
||||
int index = BinarySearch.search(nums, target);
|
||||
// 应该注意这里的下标必须大于 j,否则会重复统计。
|
||||
if (index > j)
|
||||
cnt++;
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -155,7 +163,8 @@ public class RatioTest {
|
|||
while (loopTimes-- > 0) {
|
||||
int[] nums = new int[N];
|
||||
StopWatch.start();
|
||||
int cnt = ThreeSum.count(nums);
|
||||
ThreeSum threeSum = new ThreeSumSlow();
|
||||
int cnt = threeSum.count(nums);
|
||||
System.out.println(cnt);
|
||||
double elapsedTime = StopWatch.elapsedTime();
|
||||
double ratio = preTime == -1 ? 0 : elapsedTime / preTime;
|
||||
|
@ -225,7 +234,7 @@ public interface MyStack<Item> extends Iterable<Item> {
|
|||
### 1. 数组实现
|
||||
|
||||
```java
|
||||
public class ResizingArrayStack<Item> implements MyStack<Item> {
|
||||
public class ArrayStack<Item> implements MyStack<Item> {
|
||||
// 栈元素数组
|
||||
private Item[] a = (Item[]) new Object[1]; // 只能通过转型来创建泛型数组
|
||||
// 元素数量
|
||||
|
|
Loading…
Reference in New Issue
Block a user