-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathGetMedian.cs
More file actions
127 lines (114 loc) · 3.61 KB
/
Copy pathGetMedian.cs
File metadata and controls
127 lines (114 loc) · 3.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
题目名称:
数据流中的中位数
题目描述:
如何得到一个数据流中的中位数?
如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。
如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
代码结构:
class Solution
{
public void Insert(int num)
{
// write code here
}
public double GetMedian()
{
// write code here
}
}
*/
using System;
namespace GetMedian {
public class TreeNode {
public TreeNode left;
public TreeNode right;
public int val;
public TreeNode(int x){
val = x;
}
}
class Solution {
/// <summary>
/// 解法1
/// 基本思路:
/// 插入时,动态构建二叉搜索树,小于根节点值的放到左子树,大于等于根节点值的放到右子树
/// 获取中位数时查找儿叉搜索树即可
/// </summary>
TreeNode root = null;
int count = 0;
int index = 0;
public void Insert(int num)
{
count ++;
if(root == null){
root = new TreeNode(num);
return;
}
TreeNode node = root;
while(true){
if(num < node.val){
if(node.left == null || node.left.val < num){
TreeNode temp = node.left;
node.left = new TreeNode(num);
node.left.left = temp;
return;
}
node = node.left;
}else{
if(node.right == null || node.right.val > num){
TreeNode temp = node.right;
node.right = new TreeNode(num);
node.right.right = temp;
return;
}
node = node.right;
}
}
}
public TreeNode GetKthNode(TreeNode pRoot, int k){
if(pRoot != null && k > 0){
TreeNode node = GetKthNode(pRoot.left, k);
if(node != null){
return node;
}
index ++;
if(index == k){
return pRoot;
}
node = GetKthNode(pRoot.right, k);
if(node != null){
return node;
}
}
return null;
}
public double GetMedian()
{
index = 0;
if(count > 0){
int median = count / 2 + 1 ;
TreeNode node = GetKthNode(root, median);
if((count & 1) == 0){
index = 0;
TreeNode last = GetKthNode(root, median - 1);
return (last.val + node.val) / 2.0d;
}else{
return node.val;
}
}
return 0;
}
/// <summary>
/// TODO 利用优先队列,构建两个堆,大顶堆和小顶堆
/// </summary>
public void Test() {
Insert(1);
Insert(3);
Insert(4);
Insert(1);
Console.WriteLine(GetMedian());
}
}
}