max{min{左max,右边max}-[i],0}
public class TrappingRainWater {
public static int water(int[] arr){
if(arr == null || arr.length==0){
return 0;
}
int N = arr.length;
int L = 1;
int leftMax = arr[0];
int R = N -2;
int rightMax = arr[N-1];
int water = 0;
while(L <= R){
if(leftMax <= rightMax){
water += Math.max(0,leftMax-arr[L]);
leftMax = Math.max(leftMax,arr[L++]);
}else{
water += Math.max(0,rightMax-arr[R]);
rightMax = Math.max(rightMax,arr[R--]);
}
}
return water;
}
}
public static class Node{
public int value;
public int row;
public int col;
public Node(int v,int r,int c){
value = v;
row = r;
col = c;
}
}
public static class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node o1, Node o2) {
return o1.value - o2.value;
}
}
public static int trapRainWater(int[][] heightMap){
if(heightMap == null || heightMap.length == 0 || heightMap[0]==null || heightMap[0].length==0){
return 0;
}
int N = heightMap.length;
int M = heightMap[0].length;
boolean[][] isEnter = new boolean[N][M];
//小根堆
PriorityQueue<Node> heap = new PriorityQueue<Node>(new NodeComparator());
//四周的进入堆
for(int col = 0;col < M - 1;col++){
isEnter[0][col] = true;
heap.add(new Node(heightMap[0][col],0,col));
}
for(int row = 0;row < N-1;row++){
isEnter[row][M-1] = true;
heap.add(new Node(heightMap[row][M-1],row,M-1));
}
for(int col = M-1;col > 0;col--){
isEnter[N-1][col] = true;
heap.add(new Node(heightMap[N-1][col],N-1,col));
}
for(int row = N-1;row>0;row--){
isEnter[row][0] = true;
heap.add(new Node(heightMap[row][0],row,0));
}
int water = 0;
int max = 0;
//弹出小根堆
while(!heap.isEmpty()){
Node cur = heap.poll();
//max更新相当于换一个湖
max =Math.max(max,cur.value);
int r = cur.row;
int c = cur.col;
if(r > 0 && !isEnter[r-1][c]){
water += Math.max(0,max -heightMap[r-1][c]);
isEnter[r-1][c] = true;
heap.add(new Node(heightMap[r-1][c],r-1,c));
}
if(r < N-1 && !isEnter[r+1][c]){
water += Math.max(0,max-heightMap[r+1][c]);
isEnter[r+1][c] = true;
heap.add(new Node(heightMap[r+1][c],r+1,c));
}
if(c > 0 && !isEnter[r][c-1]){
water += Math.max(0,max-heightMap[r][c-1]);
isEnter[r][c-1] = true;
heap.add(new Node(heightMap[r][c-1],r,c-1));
}
}
return water;
}
public class KthMinPair {
public static int[] kthMinPair3(int[] arr,int k){
int N = arr.length;
if(k > N * N ){
return null;
}
int fristNum = getMinkth(arr,(k-1)/N);//数学
int lessFirstNumSize = 0;
int firstNumSize = 0;
for (int i = 0; i < N; i++) {
if(arr[i] < fristNum){
lessFirstNumSize++;
}
if(arr[i] == fristNum){
firstNumSize++;
}
}
int res = k - lessFirstNumSize * N;
return new int[] {fristNum,getMinkth(arr,(res-1)/firstNumSize)};
}
//快排 找arr[index]
public static int getMinkth(int[] arr,int index){
int L = 0;
int R = arr.length-1;
int pivot =0;
int[] range = null;
while(L < R){
pivot = arr[L+(int)(Math.random()*(R-L+1))];
range = partition(arr,L,R,pivot);
if(index < range[0]){
R = range[0] -1;
}else if(index > range[1]){
L = range[1] + 1;
}else{
return pivot;
}
}
return arr[L];
}
}