Skip to content

Commit 977e27a

Browse files
committed
slidingWindowMaximum, Search2DMatrix, ReserseWord2
1 parent 0b14e5e commit 977e27a

File tree

11 files changed

+407
-94
lines changed

11 files changed

+407
-94
lines changed

src/main/java/joshua/leetcode/bits/ReverseBits.java

Lines changed: 42 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,47 @@
22

33
public class ReverseBits {
44

5-
/**
6-
* Reverse bits of a given 32 bits unsigned integer.
7-
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
8-
return 964176192 (represented in binary as 00111001011110000010100101000000).
9-
10-
*/
5+
/**
6+
* Reverse bits of a given 32 bits unsigned integer.
7+
* For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
8+
* return 964176192 (represented in binary as 00111001011110000010100101000000).
9+
*/
1110

12-
// you need treat n as an unsigned value
13-
public int reverseBits(int n) {
14-
if(n==1)
15-
return Integer.MIN_VALUE;
16-
String bitStr = Integer.toBinaryString(n);
17-
StringBuilder sBuilder = new StringBuilder();
18-
for (int i = bitStr.length() - 1; i > -1; i--) {
19-
sBuilder.append(bitStr.substring(i, i + 1));
20-
}
21-
for (int j = 1; j <= 32 - bitStr.length(); j++)
22-
sBuilder.append("0");
23-
String outStr=sBuilder.toString();
24-
if(outStr.startsWith("0"))
25-
return Integer.parseInt(outStr, 2);
26-
sBuilder=new StringBuilder();
27-
sBuilder.append(0);
28-
for (int i = 1; i <32; i++) {
29-
sBuilder.append(outStr.substring(i, i + 1).endsWith("0")?"1":"0");
30-
}
31-
return 0-(Integer.parseInt(sBuilder.toString().trim(), 2)+1);
32-
}
33-
34-
/**
35-
* Parse 32-bit string into signed integer
36-
* @return
37-
*/
38-
public static int parseFromBitStr(String bitStr){
39-
if(bitStr.startsWith("0"))
40-
return Integer.parseInt(bitStr, 2);
41-
StringBuilder sBuilder=new StringBuilder();
42-
sBuilder.append(0);
43-
for (int i = 1; i <32; i++) {
44-
sBuilder.append(bitStr.substring(i, i + 1)=="0"?"1":"0");
45-
}
46-
return 0-(Integer.parseInt(sBuilder.toString().trim(), 2)+1);
47-
}
11+
// you need treat n as an unsigned value
12+
public int reverseBits(int n) {
13+
if (n == 1)
14+
return Integer.MIN_VALUE;
15+
String bitStr = Integer.toBinaryString(n);
16+
StringBuilder sBuilder = new StringBuilder();
17+
for (int i = bitStr.length() - 1; i > -1; i--) {
18+
sBuilder.append(bitStr.substring(i, i + 1));
19+
}
20+
for (int j = 1; j <= 32 - bitStr.length(); j++)
21+
sBuilder.append("0");
22+
String outStr = sBuilder.toString();
23+
if (outStr.startsWith("0"))
24+
return Integer.parseInt(outStr, 2);
25+
sBuilder = new StringBuilder();
26+
sBuilder.append(0);
27+
for (int i = 1; i < 32; i++) {
28+
sBuilder.append(outStr.substring(i, i + 1).endsWith("0") ? "1" : "0");
29+
}
30+
return 0 - (Integer.parseInt(sBuilder.toString().trim(), 2) + 1);
31+
}
32+
33+
/**
34+
* Parse 32-bit string into signed integer
35+
*
36+
* @return
37+
*/
38+
public static int parseFromBitStr(String bitStr) {
39+
if (bitStr.startsWith("0"))
40+
return Integer.parseInt(bitStr, 2);
41+
StringBuilder sBuilder = new StringBuilder();
42+
sBuilder.append(0);
43+
for (int i = 1; i < 32; i++) {
44+
sBuilder.append(bitStr.substring(i, i + 1) == "0" ? "1" : "0");
45+
}
46+
return 0 - (Integer.parseInt(sBuilder.toString().trim(), 2) + 1);
47+
}
4848
}

src/main/java/joshua/leetcode/divideconquer/Search2DMatrixII.java

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,35 @@ public abstract class Search2DMatrixII {
3434
public abstract boolean searchMatrix(int[][] matrix, int target);
3535

3636
/**
37-
* 观察矩阵可以发现, 每个对角线上的元素matrix[i,i]都大于所有其他index小于i的元素,即该元素的左上角的矩阵。
38-
* 因此可以先对对角线上元素做二分查找。
37+
* 观察矩阵可以发现, 斜对角线上的每个元素matrix[i,j]都是对应的列的最小元素,是对应的行的最大元素。
38+
* 因此可以比较斜对角线上的最右上角元素ele和target的大小关系:
39+
* 如果ele > target, 可以过滤掉ele对应的行
40+
* 如果ele < target, 可以过滤掉ele对应的列
41+
* 如果相等可以直接返回。
42+
*
43+
* 这样每次比较都可以过滤掉一行,或者一列,总的时间复杂度就是o(m+n)
3944
*
4045
*/
4146
public static class Solution1 extends Search2DMatrixII {
4247

4348
@Override
4449
public boolean searchMatrix(int[][] matrix, int target) {
45-
50+
if(matrix == null || matrix[0] == null || matrix[0].length == 0) {
51+
return false;
52+
}
53+
int row = matrix.length, col = matrix[0].length;
54+
int i = 0, j = col - 1;
55+
while(i < row && j > -1) {
56+
int ele = matrix[i][j];
57+
if (ele < target) {
58+
i++;
59+
} else if (ele > target) {
60+
j--;
61+
} else {
62+
return true;
63+
}
64+
}
65+
return false;
4666
}
4767
}
4868
}
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
package joshua.leetcode.heap;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Deque;
5+
6+
/**
7+
* 239. Sliding Window Maximum<br/>
8+
* <p/>
9+
* <a href="https://leetcode.com/problems/sliding-window-maximum/">leetcode link</a>
10+
*
11+
* @author Jiang Yong ([email protected])
12+
*/
13+
public abstract class SlidingWindowMaximum {
14+
15+
/**
16+
* Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
17+
* <p/>
18+
* For example,
19+
* Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
20+
* <p/>
21+
* Window position Max
22+
* --------------- -----
23+
* [1 3 -1] -3 5 3 6 7 3
24+
* 1 [3 -1 -3] 5 3 6 7 3
25+
* 1 3 [-1 -3 5] 3 6 7 5
26+
* 1 3 -1 [-3 5 3] 6 7 5
27+
* 1 3 -1 -3 [5 3 6] 7 6
28+
* 1 3 -1 -3 5 [3 6 7] 7
29+
* Therefore, return the max sliding window as [3,3,5,5,6,7].
30+
* <p/>
31+
* Note:
32+
* You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.
33+
* <p/>
34+
* Follow up:
35+
* Could you solve it in linear time?
36+
*/
37+
public abstract int[] maxSlidingWindow(int[] nums, int k);
38+
39+
40+
/**
41+
* 使用双端队列(Deque).
42+
* 使用双端队列的原因是一要保持队列内的元素保持元素的本来顺序,同时提供了类似Stack的操作可以在插入
43+
* 端删除元素。
44+
*/
45+
public static class Solution1 extends SlidingWindowMaximum {
46+
47+
@Override
48+
public int[] maxSlidingWindow(int[] nums, int k) {
49+
// store the index other than value
50+
Deque<Integer> deque = new ArrayDeque<Integer>();
51+
// store the maximum of all windows, 1 <=k <= nums.length
52+
int[] result = new int[nums.length - k + 1];
53+
for (int i = 0; i < nums.length; i++) {
54+
55+
//step 1. remove all elements with index smaller than i-k+1 from the
56+
//head of the deque, 'cause they are left out of the siding window
57+
while (!deque.isEmpty() && deque.peek() < i - k + 1) {
58+
//remove from the head of the deque, poll() equals pollFirst()
59+
deque.poll();
60+
}
61+
62+
//step 2: examine the element from the tail of deque, pop it if it's smaller than
63+
//nums[i], cause for elements smaller than nums[i], they won't have
64+
//a chance to become the maximum in the sliding window.
65+
while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
66+
deque.pollLast();
67+
}
68+
69+
//step 3: put the new index into the tail of the deque by offer() method
70+
deque.offer(i);
71+
72+
//step 4: for every i larger than k-1, calculate the maximum element of sliding
73+
//window represented by [i-k+1, i]
74+
if (i >= k - 1) {
75+
result[i - k + 1] = nums[deque.peek()];
76+
}
77+
}
78+
return result;
79+
}
80+
}
81+
82+
/**
83+
* For Example: nums = [2,1,3,4,6,3,8,9,10,12,56], w=4
84+
* <p/>
85+
* partition the array in blocks of size w=4. The last block may have less then w. 2, 1, 3, 4 | 6, 3, 8, 9 | 10, 12, 56|
86+
* <p/>
87+
* Traverse the list from start to end and calculate max so far. Reset max after each block boundary (of w
88+
* elements).
89+
* left_max[] = 2, 2, 3, 4 | 6, 6, 8, 9 | 10, 12, 56
90+
* <p/>
91+
* Similarly calculate max in future by traversing from end to start.
92+
* right_max[] = 4, 4, 4, 4 | 9, 9, 9, 9 | 56, 56, 56
93+
* <p/>
94+
* now, sliding max at each position i in current window, sliding-max(i) = max{rightmax(i), leftmax(i+w-1)}
95+
*
96+
* sliding_max = 4, 6, 6, 8, 9, 10, 12, 56
97+
* <p/>
98+
*
99+
* <a href = "https://leetcode.com/discuss/62695/o-n-solution-in-java-with-two-simple-pass-in-the-array">leetcode
100+
* 讨论解法链接</a>
101+
*/
102+
public static class Solution2 extends SlidingWindowMaximum {
103+
104+
@Override
105+
public int[] maxSlidingWindow(int[] nums, int k) {
106+
if(nums == null || nums.length == 0) {
107+
return new int[]{};
108+
}
109+
110+
/*for each window, maximum element from left to right*/
111+
int[] max_left = new int[nums.length];
112+
/*for each window, maximum element from right to left*/
113+
int[] max_right = new int[nums.length];
114+
115+
max_left[0] = nums[0];
116+
max_right[nums.length - 1] = nums[nums.length - 1];
117+
118+
for (int i = 1; i < nums.length; i++) {
119+
max_left[i] = (i % k == 0) ? nums[i] : Math.max(max_left[i - 1], nums[i]);
120+
121+
final int j = nums.length - i - 1;
122+
max_right[j] = (j % k == 0) ? nums[j] : Math.max(max_right[j + 1], nums[j]);
123+
}
124+
125+
// having nums.length-k+1 windows in the nums array
126+
int[] sliding_max = new int[nums.length - k + 1];
127+
128+
for (int i = 0; i + k <= nums.length; i++) {
129+
sliding_max[i] = Math.max(max_right[i], max_left[i + k - 1]);
130+
}
131+
132+
return sliding_max;
133+
}
134+
}
135+
}

src/main/java/joshua/leetcode/heap/TopKFrequentElements.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,10 @@ public List<Integer> topKFrequent(int[] nums, int k) {
6565
Arrays.sort(nums);
6666
Map<Integer, List<Integer>> frequencyBucket = new HashMap<Integer, List<Integer>>();
6767
int maxFrequency = 0;
68+
/**
69+
* 记录下每个number的frequency,相同frequency的numer是存储在同一个key下面的,key就是frequency的值,
70+
* 同时记录下最大的frequency.
71+
*/
6872
for (int i = 0; i < nums.length; i++) {
6973
int count = 1;
7074
while (i + 1 < nums.length && nums[i] == nums[i + 1]) {
@@ -79,6 +83,9 @@ public List<Integer> topKFrequent(int[] nums, int k) {
7983
}
8084
List<Integer> topK = new ArrayList<Integer>();
8185
int size = 0;
86+
/**
87+
* 从maxFrequency递减查找frequencyBucket
88+
*/
8289
for (int i = maxFrequency; i > 0; i--) {
8390
if (!frequencyBucket.containsKey(i)) {
8491
continue;

src/main/java/joshua/leetcode/strings/LongestCommonPrefix.java

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,53 +2,53 @@
22

33
/**
44
* 14 Longest Common Prefix
5-
* @see <a href="https://leetcode.com/problems/longest-common-prefix/">leetcode link</a>
6-
* @author joy
75
*
6+
* @author joy
7+
* @see <a href="https://leetcode.com/problems/longest-common-prefix/">leetcode link</a>
88
*/
99
public abstract class LongestCommonPrefix {
1010

11-
/**
12-
* Write a function to find the longest common prefix string amongst an array of strings.
13-
*
14-
* @param strs
15-
* @return
16-
*/
17-
public abstract String longestCommonPrefix(String[] strs);
18-
19-
static class Solution1 extends LongestCommonPrefix{
11+
/**
12+
* Write a function to find the longest common prefix string amongst an array of strings.
13+
*
14+
* @param strs
15+
* @return
16+
*/
17+
public abstract String longestCommonPrefix(String[] strs);
18+
19+
static class Solution1 extends LongestCommonPrefix {
20+
21+
@Override
22+
public String longestCommonPrefix(String[] strs) {
23+
if (strs == null || strs.length == 0)
24+
return "";
25+
String str = strs[0];
26+
int end = 0;
27+
boolean flag = false;/*whether comparison is over*/
28+
if (str == null || str.length() == 0)
29+
return "";
30+
if (strs.length == 1)
31+
return str;
32+
while (end < strs[0].length()) {
33+
for (int i = 1; i < strs.length; i++) {
34+
if (strs[i] == null || strs[i].length() - 1 < end) {
35+
flag = true;
36+
break;
37+
}
38+
if (strs[i].charAt(end) != str.charAt(end)) {
39+
flag = true;
40+
break;
41+
}
42+
}
43+
if (!flag)
44+
end++;
45+
else {
46+
if (end == 0) end = -1;
47+
break;
48+
}
49+
}
50+
return end == -1 ? "" : str.substring(0, end);
51+
}
2052

21-
@Override
22-
public String longestCommonPrefix(String[] strs) {
23-
if(strs==null||strs.length==0)
24-
return "";
25-
String str=strs[0];
26-
int end=0;
27-
boolean flag=false;/*whether comparison is over*/
28-
if(str==null||str.length()==0)
29-
return "";
30-
if(strs.length==1)
31-
return str;
32-
while(end<strs[0].length()){
33-
for(int i=1;i<strs.length;i++){
34-
if(strs[i]==null||strs[i].length()-1<end){
35-
flag=true;
36-
break;
37-
}
38-
if(strs[i].charAt(end)!=str.charAt(end)){
39-
flag=true;
40-
break;
41-
}
42-
}
43-
if(!flag)
44-
end++;
45-
else{
46-
if(end==0) end=-1;
47-
break;
48-
}
49-
}
50-
return end==-1?"":str.substring(0, end);
51-
}
52-
53-
}
53+
}
5454
}

0 commit comments

Comments
 (0)