Skip to content

Commit dcbaa89

Browse files
committedMay 20, 2019
2019-5-20
1 parent 2b833f2 commit dcbaa89

File tree

285 files changed

+7252
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

285 files changed

+7252
-0
lines changed
 
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public int[] twoSum(int[] nums, int target) {
3+
Map<Integer, Integer> map = new HashMap<>();
4+
for (int i = 0; i< nums.length; i++){
5+
int complement = target - nums[i];
6+
if (map.containsKey(complement)){
7+
return new int[]{map.get(complement), i};
8+
}
9+
map.put(nums[i], i);
10+
}
11+
return new int[]{};
12+
}
13+
14+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from heapq import *
2+
class MedianFinder(object):
3+
# 维护两个堆,一个大顶堆,一个小顶堆,小顶堆里的数比大顶堆里的数都要大,
4+
# 如果有两个潜在的中位数(两个堆size相同),数据流的中位数就是两个堆顶之和除以2
5+
# 如果只有一个中位数,就看size更小的那个堆的堆顶
6+
# 如果新进来的数比小顶堆的数要小,就把它插入大顶堆
7+
# 如果新进来的数比小顶堆的数要大,就把它插入小顶堆
8+
# 调整两个堆,使得size 差最大为1
9+
def __init__(self):
10+
"""
11+
initialize your data structure here.
12+
"""
13+
self.max_h = list()
14+
self.min_h = list()
15+
heapify(self.max_h)
16+
heapify(self.min_h)
17+
18+
19+
def addNum(self, num):
20+
"""
21+
:type num: int
22+
:rtype: None
23+
"""
24+
heappush(self.min_h, num)
25+
heappush(self.max_h, -heappop(self.min_h))
26+
if len(self.max_h) > len(self.min_h):
27+
heappush(self.min_h, -heappop(self.max_h))
28+
29+
def findMedian(self):
30+
"""
31+
:rtype: float
32+
"""
33+
max_len = len(self.max_h)
34+
min_len = len(self.min_h)
35+
if max_len == min_len: #有两个候选中位数
36+
return (self.min_h[0] + -self.max_h[0]) / 2.
37+
else:#小顶堆的size 一定 >= 大顶堆的size,所以答案就是小顶堆的堆顶
38+
return self.min_h[0] / 1.
39+
40+
# Your MedianFinder object will be instantiated and called as such:
41+
# obj = MedianFinder()
42+
# obj.addNum(num)
43+
# param_2 = obj.findMedian()
44+
45+
class Solution(object):
46+
def findMedianSortedArrays(self, nums1, nums2):
47+
"""
48+
:type nums1: List[int]
49+
:type nums2: List[int]
50+
:rtype: float
51+
"""
52+
mf = MedianFinder()
53+
for num in nums1:
54+
mf.addNum(num)
55+
for num in nums2:
56+
mf.addNum(num)
57+
return mf.findMedian()

0 commit comments

Comments
 (0)