本文主要是介绍算法打卡——接雨水和动物收容所 java,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
接雨水:https://leetcode-cn.com/problems/trapping-rain-water/
class Solution {public int trap(int[] height) {int n=height.length;if(n==0){return 0;}int[] leftMax=new int[n];int[] rightMax=new int[n];leftMax[0]=height[0];for(int i=1;i<n;i++){leftMax[i]=Math.max(leftMax[i-1],height[i]);}rightMax[n-1]=height[n-1];for(int i=n-2;i>=0;i--){rightMax[i]=Math.max(rightMax[i+1],height[i]);}int sum=0;for(int i=0;i<n;i++){sum+=Math.min(leftMax[i],rightMax[i])-height[i];}return sum;}
}
动物收容所: https://leetcode-cn.com/problems/animal-shelter-lcci/
class AnimalShelf {public Deque<Integer> catDeque=new LinkedList<>();public Deque<Integer> dogDeque=new LinkedList<>();public AnimalShelf() {}public void enqueue(int[] animal) {if(animal.length==2){if(animal[1]==0){catDeque.offer(animal[0]);}else if(animal[1]==1){dogDeque.offer(animal[0]);}}}public int[] dequeueAny() {int num=-1;int kind=-1;int oldDog=-1;int oldCat=-1;if(!dogDeque.isEmpty()){oldDog=dogDeque.peekFirst();}if(!catDeque.isEmpty()){oldCat=catDeque.peekFirst();}if(oldDog==-1){num=oldCat;if(num!=-1){kind=0;}}else if(oldCat==-1){num=oldDog;kind=1;}else {if(oldCat<oldDog){num=oldCat;kind=0;}else{num=oldDog;kind=1;}}if(kind==1){dogDeque.pollFirst();}if(kind==0){catDeque.pollFirst();}return new int[]{num,kind};}public int[] dequeueDog() {int num=-1;int kind=-1;if(!dogDeque.isEmpty()){num=dogDeque.pollFirst();kind=1;}return new int[]{num,kind};}public int[] dequeueCat() {int num=-1;int kind=-1;if(!catDeque.isEmpty()){num=catDeque.pollFirst();kind=0;}return new int[]{num,kind};}
}/*** Your AnimalShelf object will be instantiated and called as such:* AnimalShelf obj = new AnimalShelf();* obj.enqueue(animal);* int[] param_2 = obj.dequeueAny();* int[] param_3 = obj.dequeueDog();* int[] param_4 = obj.dequeueCat();*/
这篇关于算法打卡——接雨水和动物收容所 java的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!