Skip to content

Commit

Permalink
Day ??? - Cross Training III
Browse files Browse the repository at this point in the history
  • Loading branch information
xckomorebi committed Oct 10, 2022
1 parent 9c42959 commit 51e8ff1
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
63 changes: 63 additions & 0 deletions CrossTrainingIII.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import java.util.*;

public class CrossTrainingIII {
/**
* Common Numbers Of Two Arrays I(Array version)
* <p>
* Find all numbers that appear in both of the two unsorted arrays, return the
* common numbers in increasing order.
*/
public List<Integer> common(int[] a, int[] b) {
Arrays.sort(a);
Arrays.sort(b);
List<Integer> result = new ArrayList<>();

int i = 0;
int j = 0;

while (i < a.length && j < b.length) {
if (a[i] == b[j]) {
result.add(a[i]);
i++;
j++;
} else if (a[i] > b[j]) {
j++;
} else {
i++;
}
}
return result;
}

/**
* Largest Rectangle In Histogram
* <p>
* Given a non-negative integer array representing the heights of a list of
* adjacent bars. Suppose each bar has a width of 1. Find the largest
* rectangular area that can be formed in the histogram.
*/
public int largest(int[] array) {
int result = 0;
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < array.length; i++) {
if (stack.isEmpty()) {
stack.offerLast(i);
} else if (array[stack.peekLast()] > array[i]) {
int prev = 0;
int prevMax = 0;
while (!stack.isEmpty() && array[stack.peekLast()] > array[i]) {
prev = stack.pollLast();
prevMax = array[prev];
}
prev = stack.isEmpty() ? -1 : prev;

result = Math.max((i - 1 - prev) * prevMax, result);
} else {
stack.offerLast(i);
}
}
result = Math.max((array.length - stack.peekFirst()) * array[stack.peekFirst()], result);

return result;
}
}
3 changes: 3 additions & 0 deletions DFSII.java
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,9 @@ public int[] keepDistance(int k) {
}

private boolean keepDistance(int[] result, int n) {
if (n == 0) {
return true;
}
for (int i = 0; i + n + 1 < result.length; i++) {
if (result[i] == 0 && result[i + n + 1] == 0) {
result[i] = n;
Expand Down

0 comments on commit 51e8ff1

Please sign in to comment.