From 5ddb1746c8c12741ee896efc2b167cf601179c72 Mon Sep 17 00:00:00 2001 From: CyC2018 <1029579233@qq.com> Date: Wed, 6 Jun 2018 21:06:12 +0800 Subject: [PATCH] auto commit --- notes/算法.md | 45 +++++++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/notes/算法.md b/notes/算法.md index 2744c56d..d1015dc7 100644 --- a/notes/算法.md +++ b/notes/算法.md @@ -67,8 +67,15 @@ N3/6-N2/2+N/3 的增长数量级为 O(N3)。增 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 extends Iterable { ### 1. 数组实现 ```java -public class ResizingArrayStack implements MyStack { +public class ArrayStack implements MyStack { // 栈元素数组 private Item[] a = (Item[]) new Object[1]; // 只能通过转型来创建泛型数组 // 元素数量