Skip to content

Commit 95e543b

Browse files
committed
countPrime,minStack,MedianFinder,DeleteNodeInLinkedList
1 parent ddd0b82 commit 95e543b

File tree

7 files changed

+283
-28
lines changed

7 files changed

+283
-28
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Copyright 2016 Baidu Inc. All rights reserved.
2+
3+
package joshua.leetcode.design;
4+
5+
import java.util.PriorityQueue;
6+
7+
/**
8+
* 295. Find Median from Data Stream<br/>
9+
* <p/>
10+
* <a href="https://leetcode.com/problems/find-median-from-data-stream/">leetcode link</a>
11+
*
12+
* @author Jiang Yong ([email protected])
13+
*/
14+
public abstract class MedianFinder {
15+
16+
/**
17+
* 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.
18+
* <p/>
19+
* Examples:
20+
* [2,3,4] , the median is 3
21+
* <p/>
22+
* [2,3], the median is (2 + 3) / 2 = 2.5
23+
* <p/>
24+
* Design a data structure that supports the following two operations:<br/>
25+
* <ul>
26+
* <li>void addNum(int num) - Add a integer number from the data stream to the data structure.</li>
27+
* <li>double findMedian() - Return the median of all elements so far.</li>
28+
* </ul>
29+
* For example:
30+
* <p/>
31+
* add(1)
32+
* add(2)
33+
* findMedian() -> 1.5
34+
* add(3)
35+
* findMedian() -> 2
36+
*/
37+
// Adds a number into the data structure.
38+
public abstract void addNum(int num);
39+
40+
// Returns the median of current data stream
41+
public abstract double findMedian();
42+
43+
44+
/**
45+
* 先明确几个用到的概念:
46+
*
47+
* 最小堆(Min Heap), 内部实现是一个数组,每次插入堆会调整元素,保证最小元素在栈顶,即数组首位。每次调整的时间复杂度为o(logn)
48+
* 最大堆(Max Heap), 保证最大元素在栈顶,其他同上。
49+
*
50+
* 本题思路是将data stream一分为二的存储在两个堆中,一个最小堆aHeap用于存储较大的一半元素,一个最大堆bHeap用于存储较小的一半元素。
51+
* 并且保持aHeap永远比bHeap大小相等或者+1。
52+
* 这样,如果两个堆大小相等,则median就是aHeap的栈顶元素和bHeap的栈顶元素的平均值;
53+
* 如果两个堆大小相差1,则median就是aHeap的栈顶元素。
54+
*
55+
* 在Java中,PriorityQueue的内部实现就是min Heap。
56+
* 这样PriorityQueue的头部对应min heap的栈顶。压入栈的操作等同于入队操作,优先队列会调整栈顶元素使其最小。
57+
* 至于MaxHeap可以使用元素的负值插入到priorityQueue中,这样队列头部的元素的相反值就是最大值了,实现了max heap的作用。
58+
*
59+
*/
60+
public static class Solution1 extends MedianFinder {
61+
62+
/**
63+
* store the larger half of the ascending stream.
64+
* like [3,4,5] in [1,2,3,4,5]
65+
*/
66+
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
67+
68+
/**
69+
* store the lower half of the ascending stream,but in negative form, mimic the functionality of max heap.
70+
* like [-2,-1] in [1,2,3,4,5]
71+
*/
72+
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>();
73+
74+
/**
75+
* mean the total number of data stream so far is even. initially it's even as zero.
76+
*/
77+
private boolean isEven = true;
78+
79+
@Override
80+
public void addNum(int num) {
81+
minHeap.offer(num);
82+
maxHeap.offer(-minHeap.poll());
83+
/*if it's even before this adding action, even maxHeap's size will exceed minHeap after the above two
84+
operations, then we need to get the largest element from the smaller part back into the larger part. */
85+
if (isEven) {
86+
minHeap.offer(-maxHeap.poll());
87+
}
88+
isEven = !isEven;
89+
}
90+
91+
@Override
92+
public double findMedian() {
93+
if(minHeap.size() == 0)
94+
return 0;
95+
if (minHeap.size() == maxHeap.size()) {
96+
return (minHeap.peek() - maxHeap.peek()) / 2.0;
97+
} else {
98+
return minHeap.peek();
99+
}
100+
}
101+
}
102+
}

src/main/java/joshua/leetcode/hashtable/GroupAnagrams.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ public static class Solution1 extends GroupAnagrams{
4747
public List<List<String>> groupAnagrams(String[] strs) {
4848
Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
4949
for (String str : strs) {
50+
// flags用来作为anagram的hash key,例如"aab", "aba"的key都是“00...000012”,前面是24个零。
5051
int[] flags = new int[26];
5152
for(char ch : str.toCharArray()) {
5253
flags[ch - 'a']++;
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright 2016 Baidu Inc. All rights reserved.
2+
3+
package joshua.leetcode.linkedlist;
4+
5+
/**
6+
* 237. Delete Node in a Linked List<br/>
7+
* <p/>
8+
* <a href="https://leetcode.com/problems/delete-node-in-a-linked-list/">leetcod link</a>
9+
*
10+
* @author Jiang Yong ([email protected])
11+
*/
12+
public abstract class DeleteNodeInLinkedList {
13+
14+
/**
15+
* Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
16+
* <p/>
17+
* Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3,
18+
* <p/>
19+
* the linked list should become 1 -> 2 -> 4 after calling your function.
20+
*
21+
* @param node the ndoe to delete from linked list
22+
*/
23+
public abstract void deleteNode(ListNode node);
24+
25+
/**
26+
* 采取复制值,不移动节点连接的方式来间接达到删除节点的结果。
27+
*/
28+
public static class Solution1 extends DeleteNodeInLinkedList {
29+
30+
@Override
31+
public void deleteNode(ListNode node) {
32+
if (node == null || node.next == null)
33+
return;
34+
node.val = node.next.val;
35+
node.next = node.next.next;
36+
}
37+
}
38+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright 2016 Baidu Inc. All rights reserved.
2+
3+
package joshua.leetcode.math;
4+
5+
/**
6+
* 204. Count Primes<br/>
7+
* <a href = "https://leetcode.com/problems/count-primes/">leetcode link</a>
8+
*
9+
* @author Jiang Yong ([email protected])
10+
*/
11+
public abstract class CountPrime {
12+
13+
/**
14+
* Count the number of prime numbers less than a non-negative number, n.
15+
* <p/>
16+
* Hint:
17+
* <p/>
18+
* Let's start with a isPrime function. To determine if a number is prime,
19+
* we need to check if it is not divisible by any number less than n.
20+
* <p/>
21+
* The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2).
22+
* <p/>
23+
* Could we do better?
24+
* <p/>
25+
* <p/>
26+
* Show More Hint
27+
*
28+
* @param n
29+
* @return
30+
*/
31+
public abstract int countPrimes(int n);
32+
33+
public static class Solution extends CountPrime {
34+
35+
@Override
36+
public int countPrimes(int n) {
37+
boolean[] notPrime = new boolean[n];
38+
int count = 0;
39+
for(int i = 2; i < n; i++) {
40+
if (!notPrime[i]) {
41+
count ++;
42+
for (int j = 2; i * j < n; j++) {
43+
notPrime[i * j] = true;
44+
}
45+
}
46+
}
47+
return count;
48+
}
49+
}
50+
}

src/main/java/joshua/leetcode/stack/MinStack.java

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,50 +3,53 @@
33
import java.util.Stack;
44

55
/**
6-
*
7-
* Design a stack that supports push, pop, top,
6+
* Design a stack that supports push, pop, top,
87
* and retrieving the minimum element in constant time.
9-
10-
push(x) -- Push element x onto stack.
11-
pop() -- Removes the element on top of the stack.
12-
top() -- Get the top element.
13-
getMin() -- Retrieve the minimum element in the stack.
14-
15-
* @author joy
8+
* <p/>
9+
* push(x) -- Push element x onto stack.
10+
* pop() -- Removes the element on top of the stack.
11+
* top() -- Get the top element.
12+
* getMin() -- Retrieve the minimum element in the stack.
1613
*
14+
* @author joy
1715
*/
1816
public class MinStack {
19-
20-
private Stack<Integer> mStack=new Stack<Integer>();
21-
/**
22-
* minStack to store the minimum values in mStack.
23-
* each value in mStack means 'I'm the smallest to the bottom of mStack'.
24-
*/
25-
private Stack<Integer> minStack=new Stack<Integer>();
26-
17+
18+
/**
19+
* 实际存储栈中的元素
20+
*/
21+
private Stack<Integer> mStack = new Stack<Integer>();
22+
23+
/**
24+
* minStack to store the minimum values about mStack.
25+
* each value in mStack means 'I'm now the smallest amongst all current elements in mStack'.
26+
*/
27+
private Stack<Integer> minStack = new Stack<Integer>();
28+
2729
public void push(int x) {
2830
mStack.push(x);
29-
if(minStack.isEmpty()){
30-
minStack.push(x);
31-
}else{
32-
int top=minStack.peek();
33-
if(top>=x)
34-
minStack.push(x);
31+
if (minStack.isEmpty()) {
32+
minStack.push(x);
33+
} else {
34+
// 如果新元素比minStack的栈顶元素小,将新元素压入栈中,新元素就是当前mStack所有元素的最小值。
35+
int top = minStack.peek();
36+
if (top >= x)
37+
minStack.push(x);
3538
}
36-
39+
3740
}
3841

3942
public void pop() {
40-
int top=mStack.pop();
41-
if(top==minStack.peek())
42-
minStack.pop();
43+
int top = mStack.pop();
44+
if (top == minStack.peek())
45+
minStack.pop();
4346
}
4447

4548
public int top() {
4649
return mStack.peek();
4750
}
4851

4952
public int getMin() {
50-
return minStack.peek();
53+
return minStack.peek();
5154
}
5255
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package joshua.leetcode.design;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.util.List;
6+
7+
import org.junit.Before;
8+
import org.junit.Test;
9+
10+
import com.google.common.collect.Lists;
11+
12+
public class MedianFinderTest {
13+
14+
private static final double DELTA = 1e-15;
15+
private List<Param> cases = Lists.newArrayList();
16+
17+
@Before
18+
public void setUp() {
19+
cases.add(new Param(6, 6));
20+
cases.add(new Param(10, 8));
21+
cases.add(new Param(2, 6));
22+
cases.add(new Param(6, 6));
23+
cases.add(new Param(5, 6));
24+
cases.add(new Param(0, 5.5));
25+
}
26+
27+
@Test
28+
public void testSolution1() {
29+
MedianFinder medianFinder = new MedianFinder.Solution1();
30+
for (Param param : cases) {
31+
medianFinder.addNum(param.add);
32+
assertEquals(param.median, medianFinder.findMedian(), DELTA);
33+
}
34+
}
35+
36+
class Param {
37+
int add;
38+
double median;
39+
40+
public Param(int add, double median) {
41+
this.add = add;
42+
this.median = median;
43+
}
44+
}
45+
46+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package joshua.leetcode.math;
2+
3+
import static org.junit.Assert.*;
4+
5+
import org.junit.Test;
6+
7+
public class CountPrimeTest {
8+
9+
@Test
10+
public void testSolution1() {
11+
CountPrime solution = new CountPrime.Solution();
12+
assertEquals(25, solution.countPrimes(100));
13+
}
14+
15+
}

0 commit comments

Comments
 (0)