Skip to content

Commit cb125b2

Browse files
committed
[Function add]
1. Add leetcode solution.
1 parent a6abaf9 commit cb125b2

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

Diff for: leetcode/292. Nim Game.md

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
## 292. Nim Game
2+
3+
### Question
4+
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
5+
6+
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
7+
8+
```
9+
Example:
10+
11+
Input: 4
12+
Output: false
13+
Explanation: If there are 4 stones in the heap, then you will never win the game;
14+
No matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
15+
```
16+
17+
### Thinking:
18+
* Method 1:
19+
* 4的倍数无法获胜。
20+
21+
```Java
22+
class Solution {
23+
public boolean canWinNim(int n) {
24+
return n % 4 != 0;
25+
}
26+
}
27+
```

Diff for: leetcode/295.Find Median from Data Stream.md

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
## 295.Find Median from Data Stream
2+
3+
### Question
4+
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
5+
For example,
6+
7+
[2,3,4], the median is 3
8+
9+
[2,3], the median is (2 + 3) / 2 = 2.5
10+
11+
Design a data structure that supports the following two operations:
12+
13+
* void addNum(int num) - Add a integer number from the data stream to the data structure.
14+
* double findMedian() - Return the median of all elements so far.
15+
16+
```
17+
Example:
18+
19+
addNum(1)
20+
addNum(2)
21+
findMedian() -> 1.5
22+
addNum(3)
23+
findMedian() -> 2
24+
```
25+
26+
### Thinking:
27+
* Method 1:
28+
* 通过堆结构来实现,堆结构是通过优先级队列实现的。
29+
* 维护一个递增堆和一个递减堆。
30+
* 通过判断两个堆的size判断总数是奇数还是偶数。
31+
32+
```Java
33+
class MedianFinder {
34+
private List<Integer> list;
35+
/** initialize your data structure here. */
36+
public MedianFinder() {
37+
this.list = new ArrayList<>();
38+
}
39+
40+
public void addNum(int num) {
41+
list.add(num);
42+
}
43+
44+
public double findMedian() {
45+
int size = list.size();
46+
if(size % 2 != 0)
47+
return (double)list.get(size / 2);
48+
else{
49+
return (double)(list.get(size / 2) + list.get(size / 2 - 1)) / 2;
50+
}
51+
}
52+
}
53+
54+
/**
55+
* Your MedianFinder object will be instantiated and called as such:
56+
* MedianFinder obj = new MedianFinder();
57+
* obj.addNum(num);
58+
* double param_2 = obj.findMedian();
59+
*/
60+
```

0 commit comments

Comments
 (0)