目的
程序 = 数据结构 + 算法
了解数据结构、算法思想、优缺点、合理运用到项目中, 常见算法:
一、数据结构
1. 堆
1.1 应用
1.2 基础特性
- 堆中某个结点的值总是不大于或不小于其父结点的值;
- 堆总是一棵完全二叉树
- 插入、删除效率O(logn)
2. 算法
2.1 查找流中的中位数
public class MediaFinder {
public static void main(String[] args) {
int[] nums = {1,2,3,4,5,6};
int[] nums1 = {4,5,1,3,2,6,0};
int[] ints = new MediaFinder().medianII(nums);
int[] ints1 = new MediaFinder().medianII(nums1);
for (int i : ints)
{
System.out.println(i);
}
System.out.println("nums 1 :");
for (int i : ints1)
{
System.out.println(i);
}
}
public int[] medianII(int[] nums) {
int count = nums.length;
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(count, new Comparator<Integer>(){
public int compare(Integer num1, Integer num2) {
return num2 - num1;
}
});
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(count);
int[] answer = new int[count];
int number = nums[0];
answer[0] = number;
for (int i = 1; i < count; i++) {
if (nums[i] > number) {
minHeap.add(nums[i]);
} else {
maxHeap.add(nums[i]);
}
if (Math.abs(maxHeap.size() - minHeap.size()) > 1) {
if (minHeap.size() > maxHeap.size()) {
maxHeap.add(number);
number = minHeap.poll();
} else {
minHeap.add(number);
number = maxHeap.poll();
}
} else {
if (maxHeap.size() - minHeap.size() == 1 && maxHeap.peek() < number) {
minHeap.add(number);
number = maxHeap.poll();
}
}
answer[i] = number;
}
return answer;
}
}