diff --git a/src/class01/Code01_SelectionSort.java b/src/class01_01/Code01_SelectionSort.java similarity index 99% rename from src/class01/Code01_SelectionSort.java rename to src/class01_01/Code01_SelectionSort.java index c9b5738..a5e4393 100644 --- a/src/class01/Code01_SelectionSort.java +++ b/src/class01_01/Code01_SelectionSort.java @@ -1,4 +1,4 @@ -package class01; +package class01_01; import java.util.Arrays; diff --git a/src/class01/Code02_BubbleSort.java b/src/class01_01/Code02_BubbleSort.java similarity index 99% rename from src/class01/Code02_BubbleSort.java rename to src/class01_01/Code02_BubbleSort.java index 14b6e47..73fa617 100644 --- a/src/class01/Code02_BubbleSort.java +++ b/src/class01_01/Code02_BubbleSort.java @@ -1,4 +1,4 @@ -package class01; +package class01_01; import java.util.Arrays; diff --git a/src/class01/Code03_InsertionSort.java b/src/class01_01/Code03_InsertionSort.java similarity index 99% rename from src/class01/Code03_InsertionSort.java rename to src/class01_01/Code03_InsertionSort.java index 7283369..5e121b9 100644 --- a/src/class01/Code03_InsertionSort.java +++ b/src/class01_01/Code03_InsertionSort.java @@ -1,4 +1,4 @@ -package class01; +package class01_01; import java.util.Arrays; diff --git a/src/class01/Code04_BSExist.java b/src/class01_01/Code04_BSExist.java similarity index 98% rename from src/class01/Code04_BSExist.java rename to src/class01_01/Code04_BSExist.java index d89be00..0ea49cd 100644 --- a/src/class01/Code04_BSExist.java +++ b/src/class01_01/Code04_BSExist.java @@ -1,4 +1,4 @@ -package class01; +package class01_01; import java.util.Arrays; diff --git a/src/class01/Code05_BSNearLeft.java b/src/class01_01/Code05_BSNearLeft.java similarity index 98% rename from src/class01/Code05_BSNearLeft.java rename to src/class01_01/Code05_BSNearLeft.java index eaf5804..a0ef0f0 100644 --- a/src/class01/Code05_BSNearLeft.java +++ b/src/class01_01/Code05_BSNearLeft.java @@ -1,4 +1,4 @@ -package class01; +package class01_01; import java.util.Arrays; diff --git a/src/class01/Code05_BSNearRight.java b/src/class01_01/Code05_BSNearRight.java similarity index 98% rename from src/class01/Code05_BSNearRight.java rename to src/class01_01/Code05_BSNearRight.java index f3b6f25..499eaac 100644 --- a/src/class01/Code05_BSNearRight.java +++ b/src/class01_01/Code05_BSNearRight.java @@ -1,4 +1,4 @@ -package class01; +package class01_01; import java.util.Arrays; diff --git a/src/class01/Code06_BSAwesome.java b/src/class01_01/Code06_BSAwesome.java similarity index 96% rename from src/class01/Code06_BSAwesome.java rename to src/class01_01/Code06_BSAwesome.java index bdca00d..e3d1d73 100644 --- a/src/class01/Code06_BSAwesome.java +++ b/src/class01_01/Code06_BSAwesome.java @@ -1,4 +1,4 @@ -package class01; +package class01_01; public class Code06_BSAwesome { diff --git a/src/class01/Test.java b/src/class01_02/Code01_Swap.java similarity index 94% rename from src/class01/Test.java rename to src/class01_02/Code01_Swap.java index a968933..aa86cf1 100644 --- a/src/class01/Test.java +++ b/src/class01_02/Code01_Swap.java @@ -1,6 +1,6 @@ -package class01; +package class01_02; -public class Test { +public class Code01_Swap { public static void main(String[] args) { diff --git a/src/class01/Code07_EvenTimesOddTimes.java b/src/class01_02/Code02_EvenTimesOddTimes.java similarity index 96% rename from src/class01/Code07_EvenTimesOddTimes.java rename to src/class01_02/Code02_EvenTimesOddTimes.java index 713d512..ad40cc0 100644 --- a/src/class01/Code07_EvenTimesOddTimes.java +++ b/src/class01_02/Code02_EvenTimesOddTimes.java @@ -1,6 +1,6 @@ -package class01; +package class01_02; -public class Code07_EvenTimesOddTimes { +public class Code02_EvenTimesOddTimes { // arr中,只有一种数,出现奇数次 public static void printOddTimesNum1(int[] arr) { diff --git a/src/class01/Code08_KM.java b/src/class01_02/Code03_KM.java similarity index 98% rename from src/class01/Code08_KM.java rename to src/class01_02/Code03_KM.java index d0dfa74..69d70c5 100644 --- a/src/class01/Code08_KM.java +++ b/src/class01_02/Code03_KM.java @@ -1,9 +1,9 @@ -package class01; +package class01_02; import java.util.HashMap; import java.util.HashSet; -public class Code08_KM { +public class Code03_KM { public static int test(int[] arr, int k, int m) { HashMap map = new HashMap<>(); diff --git a/src/class02/Code01_ReverseList.java b/src/class02_03/Code01_ReverseList.java similarity index 99% rename from src/class02/Code01_ReverseList.java rename to src/class02_03/Code01_ReverseList.java index df53140..e055459 100644 --- a/src/class02/Code01_ReverseList.java +++ b/src/class02_03/Code01_ReverseList.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; import java.util.ArrayList; import java.util.List; diff --git a/src/class02/Code02_DeleteGivenValue.java b/src/class02_03/Code02_DeleteGivenValue.java similarity index 96% rename from src/class02/Code02_DeleteGivenValue.java rename to src/class02_03/Code02_DeleteGivenValue.java index c928085..921cc3a 100644 --- a/src/class02/Code02_DeleteGivenValue.java +++ b/src/class02_03/Code02_DeleteGivenValue.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; public class Code02_DeleteGivenValue { diff --git a/src/class02/Code03_DoubleEndsQueueToStackAndQueue.java b/src/class02_03/Code03_DoubleEndsQueueToStackAndQueue.java similarity index 99% rename from src/class02/Code03_DoubleEndsQueueToStackAndQueue.java rename to src/class02_03/Code03_DoubleEndsQueueToStackAndQueue.java index 989096a..3ac6763 100644 --- a/src/class02/Code03_DoubleEndsQueueToStackAndQueue.java +++ b/src/class02_03/Code03_DoubleEndsQueueToStackAndQueue.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; import java.util.LinkedList; import java.util.Queue; diff --git a/src/class02/Code04_RingArray.java b/src/class02_03/Code04_RingArray.java similarity index 97% rename from src/class02/Code04_RingArray.java rename to src/class02_03/Code04_RingArray.java index 4b67c7b..a0716ef 100644 --- a/src/class02/Code04_RingArray.java +++ b/src/class02_03/Code04_RingArray.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; public class Code04_RingArray { diff --git a/src/class02/Code05_GetMinStack.java b/src/class02_03/Code05_GetMinStack.java similarity index 99% rename from src/class02/Code05_GetMinStack.java rename to src/class02_03/Code05_GetMinStack.java index 0173d94..26371f0 100644 --- a/src/class02/Code05_GetMinStack.java +++ b/src/class02_03/Code05_GetMinStack.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; import java.util.Stack; diff --git a/src/class02/Code06_TwoStacksImplementQueue.java b/src/class02_03/Code06_TwoStacksImplementQueue.java similarity index 98% rename from src/class02/Code06_TwoStacksImplementQueue.java rename to src/class02_03/Code06_TwoStacksImplementQueue.java index 9144770..1a9dcd0 100644 --- a/src/class02/Code06_TwoStacksImplementQueue.java +++ b/src/class02_03/Code06_TwoStacksImplementQueue.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; import java.util.Stack; diff --git a/src/class02/Code07_TwoQueueImplementStack.java b/src/class02_03/Code07_TwoQueueImplementStack.java similarity index 98% rename from src/class02/Code07_TwoQueueImplementStack.java rename to src/class02_03/Code07_TwoQueueImplementStack.java index 49a87c1..89bc5cb 100644 --- a/src/class02/Code07_TwoQueueImplementStack.java +++ b/src/class02_03/Code07_TwoQueueImplementStack.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; import java.util.LinkedList; import java.util.Queue; diff --git a/src/class02/Code08_GetMax.java b/src/class02_03/Code08_GetMax.java similarity index 96% rename from src/class02/Code08_GetMax.java rename to src/class02_03/Code08_GetMax.java index fde30b3..6ccb006 100644 --- a/src/class02/Code08_GetMax.java +++ b/src/class02_03/Code08_GetMax.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; public class Code08_GetMax { diff --git a/src/class02/HashMapAndSortedMap.java b/src/class02_03/HashMapAndSortedMap.java similarity index 95% rename from src/class02/HashMapAndSortedMap.java rename to src/class02_03/HashMapAndSortedMap.java index 6a7477a..440e278 100644 --- a/src/class02/HashMapAndSortedMap.java +++ b/src/class02_03/HashMapAndSortedMap.java @@ -1,4 +1,4 @@ -package class02; +package class02_03; import java.util.HashMap; import java.util.HashSet; diff --git a/src/class03/Code01_MergeSort.java b/src/class03_04/Code01_MergeSort.java similarity index 92% rename from src/class03/Code01_MergeSort.java rename to src/class03_04/Code01_MergeSort.java index 50c1664..154545f 100644 --- a/src/class03/Code01_MergeSort.java +++ b/src/class03_04/Code01_MergeSort.java @@ -1,9 +1,7 @@ -package class03; +package class03_04; public class Code01_MergeSort { - - // 递归方法实现 public static void mergeSort1(int[] arr) { if (arr == null || arr.length < 2) { @@ -12,8 +10,10 @@ public class Code01_MergeSort { process(arr, 0, arr.length - 1); } - // arr[L...R]范围上,变成有序的 - // L...R N T(N) = 2*T(N/2) + O(N) -> + // 请把arr[L..R]排有序 + // l...r N + // T(N) = 2 * T(N / 2) + O(N) + // O(N * logN) public static void process(int[] arr, int L, int R) { if (L == R) { // base case return; @@ -50,21 +50,22 @@ public class Code01_MergeSort { return; } int N = arr.length; - int mergeSize = 1;// 当前有序的,左组长度 + // 步长 + int mergeSize = 1; while (mergeSize < N) { // log N + // 当前左组的,第一个位置 int L = 0; - // 0.... while (L < N) { - // L...M 左组(mergeSize) int M = L + mergeSize - 1; if (M >= N) { break; } - // L...M M+1...R(mergeSize) int R = Math.min(M + mergeSize, N - 1); + // L .... M M + 1..... R merge(arr, L, M, R); L = R + 1; } + // 防止溢出 if (mergeSize > N / 2) { break; } diff --git a/src/class03/Code02_SmallSum.java b/src/class03_04/Code02_SmallSum.java similarity index 99% rename from src/class03/Code02_SmallSum.java rename to src/class03_04/Code02_SmallSum.java index bddae7d..0211b51 100644 --- a/src/class03/Code02_SmallSum.java +++ b/src/class03_04/Code02_SmallSum.java @@ -1,4 +1,4 @@ -package class03; +package class03_04; public class Code02_SmallSum { diff --git a/src/class03/Code03_ReversePair.java b/src/class03_04/Code03_ReversePair.java similarity index 99% rename from src/class03/Code03_ReversePair.java rename to src/class03_04/Code03_ReversePair.java index 1c3f90b..524b769 100644 --- a/src/class03/Code03_ReversePair.java +++ b/src/class03_04/Code03_ReversePair.java @@ -1,4 +1,4 @@ -package class03; +package class03_04; public class Code03_ReversePair { diff --git a/src/class03/Code04_BiggerThanRightTwice.java b/src/class03_04/Code04_BiggerThanRightTwice.java similarity index 94% rename from src/class03/Code04_BiggerThanRightTwice.java rename to src/class03_04/Code04_BiggerThanRightTwice.java index 6c6afc1..6b04d66 100644 --- a/src/class03/Code04_BiggerThanRightTwice.java +++ b/src/class03_04/Code04_BiggerThanRightTwice.java @@ -1,4 +1,4 @@ -package class03; +package class03_04; public class Code04_BiggerThanRightTwice { @@ -19,14 +19,19 @@ public class Code04_BiggerThanRightTwice { } public static int merge(int[] arr, int L, int m, int r) { + // [L....M] [M+1....R] + int ans = 0; + // 目前囊括进来的数,是从[M+1, windowR) int windowR = m + 1; for (int i = L; i <= m; i++) { - while (windowR <= r && arr[i] > (arr[windowR] << 1)) { + while (windowR <= r && arr[i] > (arr[windowR] * 2)) { windowR++; } ans += windowR - m - 1; } + + int[] help = new int[r - L + 1]; int i = 0; int p1 = L; diff --git a/src/class03_05/Code01_CountOfRangeSum.java b/src/class03_05/Code01_CountOfRangeSum.java new file mode 100644 index 0000000..d9f42bb --- /dev/null +++ b/src/class03_05/Code01_CountOfRangeSum.java @@ -0,0 +1,62 @@ +package class03_05; + +// 这道题直接在leetcode测评: +// https://leetcode.com/problems/count-of-range-sum/ +public class Code01_CountOfRangeSum { + + public static int countRangeSum(int[] nums, int lower, int upper) { + if (nums == null || nums.length == 0) { + return 0; + } + long[] sum = new long[nums.length]; + sum[0] = nums[0]; + for (int i = 1; i < nums.length; i++) { + sum[i] = sum[i - 1] + nums[i]; + } + return process(sum, 0, sum.length - 1, lower, upper); + } + + public static int process(long[] sum, int L, int R, int lower, int upper) { + if (L == R) { + return sum[L] >= lower && sum[L] <= upper ? 1 : 0; + } + int M = L + ((R - L) >> 1); + return process(sum, L, M, lower, upper) + process(sum, M + 1, R, lower, upper) + + merge(sum, L, M, R, lower, upper); + } + + public static int merge(long[] arr, int L, int M, int R, int lower, int upper) { + int ans = 0; + int windowL = L; + int windowR = L; + for (int i = M + 1; i <= R; i++) { + long min = arr[i] - upper; + long max = arr[i] - lower; + while (windowR <= M && arr[windowR] <= max) { + windowR++; + } + while (windowL <= M && arr[windowL] < min) { + windowL++; + } + ans += Math.max(0, windowR - windowL); + } + long[] help = new long[R - L + 1]; + int i = 0; + int p1 = L; + int p2 = M + 1; + while (p1 <= M && p2 <= R) { + help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++]; + } + while (p1 <= M) { + help[i++] = arr[p1++]; + } + while (p2 <= R) { + help[i++] = arr[p2++]; + } + for (i = 0; i < help.length; i++) { + arr[L + i] = help[i]; + } + return ans; + } + +} diff --git a/src/class03/Code05_PartitionAndQuickSort.java b/src/class03_05/Code02_PartitionAndQuickSort.java similarity index 98% rename from src/class03/Code05_PartitionAndQuickSort.java rename to src/class03_05/Code02_PartitionAndQuickSort.java index 0677e28..7f623a2 100644 --- a/src/class03/Code05_PartitionAndQuickSort.java +++ b/src/class03_05/Code02_PartitionAndQuickSort.java @@ -1,6 +1,6 @@ -package class03; +package class03_05; -public class Code05_PartitionAndQuickSort { +public class Code02_PartitionAndQuickSort { public static void swap(int[] arr, int i, int j) { int tmp = arr[i]; diff --git a/src/class03/Code06_QuickSortRecursiveAndUnrecursive.java b/src/class03_05/Code03_QuickSortRecursiveAndUnrecursive.java similarity index 98% rename from src/class03/Code06_QuickSortRecursiveAndUnrecursive.java rename to src/class03_05/Code03_QuickSortRecursiveAndUnrecursive.java index f24ac56..f567345 100644 --- a/src/class03/Code06_QuickSortRecursiveAndUnrecursive.java +++ b/src/class03_05/Code03_QuickSortRecursiveAndUnrecursive.java @@ -1,8 +1,8 @@ -package class03; +package class03_05; import java.util.Stack; -public class Code06_QuickSortRecursiveAndUnrecursive { +public class Code03_QuickSortRecursiveAndUnrecursive { // 荷兰国旗问题 public static int[] netherlandsFlag(int[] arr, int L, int R) { diff --git a/src/class04/Code03_Heap02.java b/src/class04/Code03_Heap02.java deleted file mode 100644 index aa0fba5..0000000 --- a/src/class04/Code03_Heap02.java +++ /dev/null @@ -1,256 +0,0 @@ -package class04; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.PriorityQueue; - -public class Code03_Heap02 { - - // 堆 - public static class MyHeap { - private ArrayList heap; - private HashMap indexMap; - private int heapSize; - private Comparator comparator; - - public MyHeap(Comparator com) { - heap = new ArrayList<>(); - indexMap = new HashMap<>(); - heapSize = 0; - comparator = com; - } - - public boolean isEmpty() { - return heapSize == 0; - } - - public int size() { - return heapSize; - } - - public boolean contains(T key) { - return indexMap.containsKey(key); - } - - public void push(T value) { - heap.add(value); - indexMap.put(value, heapSize); - heapInsert(heapSize++); - } - - public T pop() { - T ans = heap.get(0); - int end = heapSize - 1; - swap(0, end); - heap.remove(end); - indexMap.remove(ans); - heapify(0, --heapSize); - return ans; - } - - public void resign(T value) { - int valueIndex = indexMap.get(value); - heapInsert(valueIndex); - heapify(valueIndex, heapSize); - } - - private void heapInsert(int index) { - while (comparator.compare(heap.get(index), heap.get((index - 1) / 2)) < 0) { - swap(index, (index - 1) / 2); - index = (index - 1) / 2; - } - } - - private void heapify(int index, int heapSize) { - int left = index * 2 + 1; - while (left < heapSize) { - int largest = left + 1 < heapSize && (comparator.compare(heap.get(left + 1), heap.get(left)) < 0) - ? left + 1 - : left; - largest = comparator.compare(heap.get(largest), heap.get(index)) < 0 ? largest : index; - if (largest == index) { - break; - } - swap(largest, index); - index = largest; - left = index * 2 + 1; - } - } - - private void swap(int i, int j) { - T o1 = heap.get(i); - T o2 = heap.get(j); - heap.set(i, o2); - heap.set(j, o1); - indexMap.put(o1, j); - indexMap.put(o2, i); - } - - } - - public static class Student { - public int classNo; - public int age; - public int id; - - public Student(int c, int a, int i) { - classNo = c; - age = a; - id = i; - } - - } - - public static class StudentComparator implements Comparator { - - @Override - public int compare(Student o1, Student o2) { - return o1.age - o2.age; - } - - } - - public static void main(String[] args) { - Student s1 = null; - Student s2 = null; - Student s3 = null; - Student s4 = null; - Student s5 = null; - Student s6 = null; - - s1 = new Student(2, 50, 11111); - s2 = new Student(1, 60, 22222); - s3 = new Student(6, 10, 33333); - s4 = new Student(3, 20, 44444); - s5 = new Student(7, 72, 55555); - s6 = new Student(1, 14, 66666); - - PriorityQueue heap = new PriorityQueue<>(new StudentComparator()); - heap.add(s1); - heap.add(s2); - heap.add(s3); - heap.add(s4); - heap.add(s5); - heap.add(s6); - while (!heap.isEmpty()) { - Student cur = heap.poll(); - System.out.println(cur.classNo + "," + cur.age + "," + cur.id); - } - - System.out.println("==============="); - - MyHeap myHeap = new MyHeap<>(new StudentComparator()); - myHeap.push(s1); - myHeap.push(s2); - myHeap.push(s3); - myHeap.push(s4); - myHeap.push(s5); - myHeap.push(s6); - while (!myHeap.isEmpty()) { - Student cur = myHeap.pop(); - System.out.println(cur.classNo + "," + cur.age + "," + cur.id); - } - - System.out.println("==============="); - - s1 = new Student(2, 50, 11111); - s2 = new Student(1, 60, 22222); - s3 = new Student(6, 10, 33333); - s4 = new Student(3, 20, 44444); - s5 = new Student(7, 72, 55555); - s6 = new Student(1, 14, 66666); - - heap = new PriorityQueue<>(new StudentComparator()); - - heap.add(s1); - heap.add(s2); - heap.add(s3); - heap.add(s4); - heap.add(s5); - heap.add(s6); - - s2.age = 6; - s4.age = 12; - s5.age = 10; - s6.age = 84; - - while (!heap.isEmpty()) { - Student cur = heap.poll(); - System.out.println(cur.classNo + "," + cur.age + "," + cur.id); - } - - System.out.println("==============="); - - s1 = new Student(2, 50, 11111); - s2 = new Student(1, 60, 22222); - s3 = new Student(6, 10, 33333); - s4 = new Student(3, 20, 44444); - s5 = new Student(7, 72, 55555); - s6 = new Student(1, 14, 66666); - - myHeap = new MyHeap<>(new StudentComparator()); - - myHeap.push(s1); - myHeap.push(s2); - myHeap.push(s3); - myHeap.push(s4); - myHeap.push(s5); - myHeap.push(s6); - - s2.age = 6; - myHeap.resign(s2); - s4.age = 12; - myHeap.resign(s4); - s5.age = 10; - myHeap.resign(s5); - s6.age = 84; - myHeap.resign(s6); - - while (!myHeap.isEmpty()) { - Student cur = myHeap.pop(); - System.out.println(cur.classNo + "," + cur.age + "," + cur.id); - } - - - - // 对数器 - System.out.println("test begin"); - int maxValue = 100000; - int pushTime = 1000000; - int resignTime = 100; - MyHeap test = new MyHeap<>(new StudentComparator()); - ArrayList list = new ArrayList<>(); - for(int i = 0 ; i < pushTime; i++) { - Student cur = new Student(1,(int) (Math.random() * maxValue), 1000); - list.add(cur); - test.push(cur); - } - for(int i = 0 ; i < resignTime; i++) { - int index = (int)(Math.random() * pushTime); - list.get(index).age = (int) (Math.random() * maxValue); - test.resign(list.get(index)); - } - int preAge = Integer.MIN_VALUE; - while(test.isEmpty()) { - Student cur = test.pop(); - if(cur.age < preAge) { - System.out.println("Oops!"); - } - preAge = cur.age; - } - System.out.println("test finish"); - - - - - - - - - - - - } - -} diff --git a/src/class04/Test.java b/src/class04/Test.java deleted file mode 100644 index ce841f9..0000000 --- a/src/class04/Test.java +++ /dev/null @@ -1,43 +0,0 @@ -package class04; - -import java.util.Comparator; -import java.util.PriorityQueue; - - -public class Test { - - // 负数,o1 放在上面的情况 - public static class MyComp implements Comparator{ - - @Override - public int compare(Integer o1, Integer o2) { - return o2 - o1; - } - - } - - - - public static void main(String[] args) { - System.out.println("hello"); - // 大根堆 - PriorityQueue heap = new PriorityQueue<>(new MyComp()); - - heap.add(5); - heap.add(7); - heap.add(3); - heap.add(0); - heap.add(2); - heap.add(5); - - while(!heap.isEmpty()) { - System.out.println(heap.poll()); - } - - - - - - } - -} diff --git a/src/class04/Code01_Comparator.java b/src/class04_06/Code01_Comparator.java similarity index 99% rename from src/class04/Code01_Comparator.java rename to src/class04_06/Code01_Comparator.java index 09c7035..ef183a0 100644 --- a/src/class04/Code01_Comparator.java +++ b/src/class04_06/Code01_Comparator.java @@ -1,4 +1,4 @@ -package class04; +package class04_06; import java.util.Arrays; import java.util.Comparator; diff --git a/src/class04/Code02_Heap01.java b/src/class04_06/Code02_Heap.java similarity index 98% rename from src/class04/Code02_Heap01.java rename to src/class04_06/Code02_Heap.java index 715289e..07ef952 100644 --- a/src/class04/Code02_Heap01.java +++ b/src/class04_06/Code02_Heap.java @@ -1,6 +1,6 @@ -package class04; +package class04_06; -public class Code02_Heap01 { +public class Code02_Heap { public static class MyMaxHeap { private int[] heap; diff --git a/src/class04/Code04_HeapSort.java b/src/class04_06/Code03_HeapSort.java similarity index 98% rename from src/class04/Code04_HeapSort.java rename to src/class04_06/Code03_HeapSort.java index 1b65638..f3d8655 100644 --- a/src/class04/Code04_HeapSort.java +++ b/src/class04_06/Code03_HeapSort.java @@ -1,9 +1,9 @@ -package class04; +package class04_06; import java.util.Arrays; import java.util.PriorityQueue; -public class Code04_HeapSort { +public class Code03_HeapSort { // 堆排序额外空间复杂度O(1) public static void heapSort(int[] arr) { diff --git a/src/class04/Code05_SortArrayDistanceLessK.java b/src/class04_06/Code04_SortArrayDistanceLessK.java similarity index 97% rename from src/class04/Code05_SortArrayDistanceLessK.java rename to src/class04_06/Code04_SortArrayDistanceLessK.java index ae986b0..bf552f5 100644 --- a/src/class04/Code05_SortArrayDistanceLessK.java +++ b/src/class04_06/Code04_SortArrayDistanceLessK.java @@ -1,9 +1,9 @@ -package class04; +package class04_06; import java.util.Arrays; import java.util.PriorityQueue; -public class Code05_SortArrayDistanceLessK { +public class Code04_SortArrayDistanceLessK { public static void sortedArrDistanceLessK(int[] arr, int k) { if (k == 0) { diff --git a/src/class04_07/Code01_CoverMax.java b/src/class04_07/Code01_CoverMax.java new file mode 100644 index 0000000..3502460 --- /dev/null +++ b/src/class04_07/Code01_CoverMax.java @@ -0,0 +1,133 @@ +package class04_07; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.PriorityQueue; + +public class Code01_CoverMax { + + public static int maxCover1(int[][] lines) { + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + for (int i = 0; i < lines.length; i++) { + min = Math.min(min, lines[i][0]); + max = Math.max(max, lines[i][1]); + } + int cover = 0; + for (double p = min + 0.5; p < max; p += 1) { + int cur = 0; + for (int i = 0; i < lines.length; i++) { + if (lines[i][0] < p && lines[i][1] > p) { + cur++; + } + } + cover = Math.max(cover, cur); + } + return cover; + } + + public static int maxCover2(int[][] m) { + Line[] lines = new Line[m.length]; + for (int i = 0; i < m.length; i++) { + lines[i] = new Line(m[i][0], m[i][1]); + } + Arrays.sort(lines, new StartComparator()); + // lines + // + PriorityQueue heap = new PriorityQueue<>(); + int max = 0; + for (int i = 0; i < lines.length; i++) { + // lines[i] -> cur 在黑盒中,把<=cur.start 东西都弹出 + while (!heap.isEmpty() && heap.peek() <= lines[i].start) { + heap.poll(); + } + heap.add(lines[i].end); + max = Math.max(max, heap.size()); + } + return max; + } + + public static class Line { + public int start; + public int end; + + public Line(int s, int e) { + start = s; + end = e; + } + } + + public static class EndComparator implements Comparator { + + @Override + public int compare(Line o1, Line o2) { + return o1.end - o2.end; + } + + } + + // for test + public static int[][] generateLines(int N, int L, int R) { + int size = (int) (Math.random() * N) + 1; + int[][] ans = new int[size][2]; + for (int i = 0; i < size; i++) { + int a = L + (int) (Math.random() * (R - L + 1)); + int b = L + (int) (Math.random() * (R - L + 1)); + if (a == b) { + b = a + 1; + } + ans[i][0] = Math.min(a, b); + ans[i][1] = Math.max(a, b); + } + return ans; + } + + public static class StartComparator implements Comparator { + + @Override + public int compare(Line o1, Line o2) { + return o1.start - o2.start; + } + + } + + public static void main(String[] args) { + + Line l1 = new Line(4, 9); + Line l2 = new Line(1, 4); + Line l3 = new Line(7, 15); + Line l4 = new Line(2, 4); + Line l5 = new Line(4, 6); + Line l6 = new Line(3, 7); + + // 底层堆结构,heap + PriorityQueue heap = new PriorityQueue<>(new StartComparator()); + heap.add(l1); + heap.add(l2); + heap.add(l3); + heap.add(l4); + heap.add(l5); + heap.add(l6); + + while (!heap.isEmpty()) { + Line cur = heap.poll(); + System.out.println(cur.start + "," + cur.end); + } + + System.out.println("test begin"); + int N = 100; + int L = 0; + int R = 200; + int testTimes = 200000; + for (int i = 0; i < testTimes; i++) { + int[][] lines = generateLines(N, L, R); + int ans1 = maxCover1(lines); + int ans2 = maxCover2(lines); + if (ans1 != ans2) { + System.out.println("Oops!"); + } + } + System.out.println("test end"); + } + +} diff --git a/src/class04_07/Code02_EveryStepShowBoss.java b/src/class04_07/Code02_EveryStepShowBoss.java new file mode 100644 index 0000000..5f10ce4 --- /dev/null +++ b/src/class04_07/Code02_EveryStepShowBoss.java @@ -0,0 +1,294 @@ +package class04_07; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; + +public class Code02_EveryStepShowBoss { + + public static class Customer { + public int value; + public int buy; + public int enterTime; + + public Customer(int v, int b, int o) { + value = v; + buy = b; + enterTime = 0; + } + } + + public static class CandidateComparator implements Comparator { + + @Override + public int compare(Customer o1, Customer o2) { + return o1.buy != o2.buy ? (o2.buy - o1.buy) : (o1.enterTime - o2.enterTime); + } + + } + + public static class DaddyComparator implements Comparator { + + @Override + public int compare(Customer o1, Customer o2) { + return o1.buy != o2.buy ? (o1.buy - o2.buy) : (o1.enterTime - o2.enterTime); + } + + } + + public static class WhosYourDaddy { + private HashMap customers; + private HeapGreater candHeap; + private HeapGreater daddyHeap; + private final int daddyLimit; + + public WhosYourDaddy(int limit) { + customers = new HashMap(); + candHeap = new HeapGreater<>(new CandidateComparator()); + daddyHeap = new HeapGreater<>(new DaddyComparator()); + daddyLimit = limit; + } + + public void operate(int time, int number, boolean buyOrRefund) { + if (!buyOrRefund && !customers.containsKey(number)) { + return; + } + if (!customers.containsKey(number)) { + customers.put(number, new Customer(number, 0, 0)); + } + Customer c = customers.get(number); + if (buyOrRefund) { + c.buy++; + } else { + c.buy--; + } + if (c.buy == 0) { + customers.remove(number); + } + if (!candHeap.contains(c) && !daddyHeap.contains(c)) { + if (daddyHeap.size() < daddyLimit) { + c.enterTime = time; + daddyHeap.push(c); + } else { + c.enterTime = time; + candHeap.push(c); + } + } else if (candHeap.contains(c)) { + if (c.buy == 0) { + candHeap.remove(c); + } else { + candHeap.resign(c); + } + } else { + if (c.buy == 0) { + daddyHeap.remove(c); + } else { + daddyHeap.resign(c); + } + } + daddyMove(time); + } + + public List getDaddies() { + List customers = daddyHeap.getAllElements(); + List ans = new ArrayList<>(); + for (Customer c : customers) { + ans.add(c.value); + } + return ans; + } + + private void daddyMove(int time) { + if (candHeap.isEmpty()) { + return; + } + if (daddyHeap.size() < daddyLimit) { + Customer p = candHeap.pop(); + p.enterTime = time; + daddyHeap.push(p); + } else { + if (candHeap.peek().buy > daddyHeap.peek().buy) { + Customer oldDaddy = daddyHeap.pop(); + Customer newDaddy = candHeap.pop(); + oldDaddy.enterTime = time; + newDaddy.enterTime = time; + daddyHeap.push(newDaddy); + candHeap.push(oldDaddy); + } + } + } + + } + + public static List> topK(int[] arr, boolean[] op, int k) { + List> ans = new ArrayList<>(); + WhosYourDaddy whoDaddies = new WhosYourDaddy(k); + for (int i = 0; i < arr.length; i++) { + whoDaddies.operate(i, arr[i], op[i]); + ans.add(whoDaddies.getDaddies()); + } + return ans; + } + + public static List> compare(int[] arr, boolean[] op, int k) { + HashMap map = new HashMap<>(); + ArrayList cands = new ArrayList<>(); + ArrayList daddy = new ArrayList<>(); + List> ans = new ArrayList<>(); + for (int i = 0; i < arr.length; i++) { + int num = arr[i]; + boolean buyOrRefund = op[i]; + if (!buyOrRefund && !map.containsKey(num)) { + ans.add(getCurAns(daddy)); + continue; + } + if (!map.containsKey(num)) { + map.put(num, new Customer(num, 0, 0)); + } + Customer c = map.get(num); + if (buyOrRefund) { + c.buy++; + } else { + c.buy--; + } + if (c.buy == 0) { + map.remove(num); + } + if (!cands.contains(c) && !daddy.contains(c)) { + if (daddy.size() < k) { + c.enterTime = i; + daddy.add(c); + } else { + c.enterTime = i; + cands.add(c); + } + } + cleanZeroBuy(cands); + cleanZeroBuy(daddy); + cands.sort(new CandidateComparator()); + daddy.sort(new DaddyComparator()); + move(cands, daddy, k, i); + ans.add(getCurAns(daddy)); + } + + return ans; + } + + public static void move(ArrayList cands, ArrayList daddy, int k, int time) { + if (cands.isEmpty()) { + return; + } + if (daddy.size() < k) { + Customer c = cands.get(0); + c.enterTime = time; + daddy.add(c); + cands.remove(0); + } else { + if (cands.get(0).buy > daddy.get(0).buy) { + Customer oldDaddy = daddy.get(0); + daddy.remove(0); + Customer newDaddy = cands.get(0); + cands.remove(0); + newDaddy.enterTime = time; + oldDaddy.enterTime = time; + daddy.add(newDaddy); + cands.add(oldDaddy); + } + } + } + + public static void cleanZeroBuy(ArrayList arr) { + List noZero = new ArrayList(); + for (Customer c : arr) { + if (c.buy != 0) { + noZero.add(c); + } + } + arr.clear(); + for (Customer c : noZero) { + arr.add(c); + } + } + + public static List getCurAns(ArrayList daddy) { + List ans = new ArrayList<>(); + for (Customer c : daddy) { + ans.add(c.value); + } + return ans; + } + + // 为了测试 + public static class Data { + public int[] arr; + public boolean[] op; + + public Data(int[] a, boolean[] o) { + arr = a; + op = o; + } + } + + // 为了测试 + public static Data randomData(int maxValue, int maxLen) { + int len = (int) (Math.random() * maxLen) + 1; + int[] arr = new int[len]; + boolean[] op = new boolean[len]; + for (int i = 0; i < len; i++) { + arr[i] = (int) (Math.random() * maxValue); + op[i] = Math.random() < 0.5 ? true : false; + } + return new Data(arr, op); + } + + // 为了测试 + public static boolean sameAnswer(List> ans1, List> ans2) { + if (ans1.size() != ans2.size()) { + return false; + } + for (int i = 0; i < ans1.size(); i++) { + List cur1 = ans1.get(i); + List cur2 = ans2.get(i); + if (cur1.size() != cur2.size()) { + return false; + } + cur1.sort((a, b) -> a - b); + cur2.sort((a, b) -> a - b); + for (int j = 0; j < cur1.size(); j++) { + if (!cur1.get(j).equals(cur2.get(j))) { + return false; + } + } + } + return true; + } + + public static void main(String[] args) { + int maxValue = 10; + int maxLen = 100; + int maxK = 6; + int testTimes = 100000; + System.out.println("测试开始"); + for (int i = 0; i < testTimes; i++) { + Data testData = randomData(maxValue, maxLen); + int k = (int) (Math.random() * maxK) + 1; + int[] arr = testData.arr; + boolean[] op = testData.op; + List> ans1 = topK(arr, op, k); + List> ans2 = compare(arr, op, k); + if (!sameAnswer(ans1, ans2)) { + for (int j = 0; j < arr.length; j++) { + System.out.println(arr[j] + " , " + op[j]); + } + System.out.println(k); + System.out.println(ans1); + System.out.println(ans2); + System.out.println("出错了!"); + break; + } + } + System.out.println("测试结束"); + } + +} diff --git a/src/class04_07/HeapGreater.java b/src/class04_07/HeapGreater.java new file mode 100644 index 0000000..e590aef --- /dev/null +++ b/src/class04_07/HeapGreater.java @@ -0,0 +1,108 @@ +package class04_07; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; + +public class HeapGreater { + + private ArrayList heap; + private HashMap indexMap; + private int heapSize; + private Comparator comp; + + public HeapGreater(Comparator c) { + heap = new ArrayList<>(); + indexMap = new HashMap<>(); + heapSize = 0; + comp = c; + } + + public boolean isEmpty() { + return heapSize == 0; + } + + public int size() { + return heapSize; + } + + public boolean contains(T obj) { + return indexMap.containsKey(obj); + } + + public T peek() { + return heap.get(0); + } + + public void push(T obj) { + heap.add(obj); + indexMap.put(obj, heapSize); + heapInsert(heapSize++); + } + + public T pop() { + T ans = heap.get(0); + swap(0, heapSize - 1); + indexMap.remove(ans); + heap.remove(--heapSize); + heapify(0); + return ans; + } + + public void remove(T obj) { + T replace = heap.get(heapSize - 1); + int index = indexMap.get(obj); + indexMap.remove(obj); + heap.remove(--heapSize); + if (obj != replace) { + heap.set(index, replace); + indexMap.put(replace, index); + resign(replace); + } + } + + public void resign(T obj) { + heapInsert(indexMap.get(obj)); + heapify(indexMap.get(obj)); + } + + public List getAllElements() { + List ans = new ArrayList<>(); + for (T c : heap) { + ans.add(c); + } + return ans; + } + + private void heapInsert(int index) { + while (comp.compare(heap.get(index), heap.get((index - 1) / 2)) < 0) { + swap(index, (index - 1) / 2); + index = (index - 1) / 2; + } + } + + private void heapify(int index) { + int left = index * 2 + 1; + while (left < heapSize) { + int best = left + 1 < heapSize && comp.compare(heap.get(left + 1), heap.get(left)) < 0 ? (left + 1) : left; + best = comp.compare(heap.get(best), heap.get(index)) < 0 ? best : index; + if (best == index) { + break; + } + swap(best, index); + index = best; + left = index * 2 + 1; + } + } + + private void swap(int i, int j) { + T o1 = heap.get(i); + T o2 = heap.get(j); + heap.set(i, o2); + heap.set(j, o1); + indexMap.put(o2, i); + indexMap.put(o1, j); + } + +} diff --git a/src/class10/Code03_TopologicalOrderBFS.java b/src/class10/Code03_TopologicalOrderBFS.java new file mode 100644 index 0000000..07f61b1 --- /dev/null +++ b/src/class10/Code03_TopologicalOrderBFS.java @@ -0,0 +1,53 @@ +package class10; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Queue; + +// OJ链接:https://www.lintcode.com/problem/topological-sorting +public class Code03_TopologicalOrderBFS { + + // 不要提交这个类 + public static class DirectedGraphNode { + public int label; + public ArrayList neighbors; + + public DirectedGraphNode(int x) { + label = x; + neighbors = new ArrayList(); + } + } + + // 提交下面的 + public static ArrayList topSort(ArrayList graph) { + HashMap indegreeMap = new HashMap<>(); + for (DirectedGraphNode cur : graph) { + indegreeMap.put(cur, 0); + } + for (DirectedGraphNode cur : graph) { + for (DirectedGraphNode next : cur.neighbors) { + indegreeMap.put(next, indegreeMap.get(next) + 1); + } + } + Queue zeroQueue = new LinkedList<>(); + for (DirectedGraphNode cur : indegreeMap.keySet()) { + if (indegreeMap.get(cur) == 0) { + zeroQueue.add(cur); + } + } + ArrayList ans = new ArrayList<>(); + while (!zeroQueue.isEmpty()) { + DirectedGraphNode cur = zeroQueue.poll(); + ans.add(cur); + for (DirectedGraphNode next : cur.neighbors) { + indegreeMap.put(next, indegreeMap.get(next) - 1); + if (indegreeMap.get(next) == 0) { + zeroQueue.offer(next); + } + } + } + return ans; + } + +} diff --git a/src/class10/Code03_TopologicalOrderDFS.java b/src/class10/Code03_TopologicalOrderDFS.java new file mode 100644 index 0000000..d15fbe6 --- /dev/null +++ b/src/class10/Code03_TopologicalOrderDFS.java @@ -0,0 +1,70 @@ +package class10; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; + +// OJ链接:https://www.lintcode.com/problem/topological-sorting +public class Code03_TopologicalOrderDFS { + + // 不要提交这个类 + public static class DirectedGraphNode { + public int label; + public ArrayList neighbors; + + public DirectedGraphNode(int x) { + label = x; + neighbors = new ArrayList(); + } + } + + // 提交下面的 + public static class Record { + public DirectedGraphNode node; + public int deep; + + public Record(DirectedGraphNode n, int o) { + node = n; + deep = o; + } + } + + public static class MyComparator implements Comparator { + + @Override + public int compare(Record o1, Record o2) { + return o2.deep - o1.deep; + } + } + + public static ArrayList topSort(ArrayList graph) { + HashMap order = new HashMap<>(); + for (DirectedGraphNode cur : graph) { + f(cur, order); + } + ArrayList recordArr = new ArrayList<>(); + for (Record r : order.values()) { + recordArr.add(r); + } + recordArr.sort(new MyComparator()); + ArrayList ans = new ArrayList(); + for (Record r : recordArr) { + ans.add(r.node); + } + return ans; + } + + public static Record f(DirectedGraphNode cur, HashMap order) { + if (order.containsKey(cur)) { + return order.get(cur); + } + int follow = 0; + for (DirectedGraphNode next : cur.neighbors) { + follow = Math.max(follow, f(next, order).deep); + } + Record ans = new Record(cur, follow + 1); + order.put(cur, ans); + return ans; + } + +}