【17】猫狗收容所

【题目】

        有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式,第一种为直接收养所有动物中最早进入收容所的,第二种为选择收养的动物类型(猫或狗),并收养该种动物中最早进入收容所的。

       给定一个操作序列int[][2] ope(C++中为vector<vector<int>>)代表所有事件。若第一个元素为1,则代表有动物进入收容所,第二个元素为动物的编号,正数代表狗,负数代表猫;若第一个元素为2,则代表有人收养动物,第二个元素若为0,则采取第一种收养方式,若为1,则指定收养狗,若为-1则指定收养猫。请按顺序返回收养的序列。若出现不合法的操作,即没有可以符合领养要求的动物,则将这次领养操作忽略。

测试样例:
[[1,1],[1,-1],[2,0],[2,-1]]
返回:[1,-1]

【代码】

import java.util.*;

public class CatDogAsylum {
    public ArrayList<Integer> asylum(int[][] ope) {
        
        ArrayList<Integer> resultList = new ArrayList<Integer>();
        
        if (ope == null || ope.length <= 0){
            return resultList;
        }
        
        ArrayList<Integer> tempList = new ArrayList<Integer>();

        int len = ope.length;
        for (int i = 0; i < len; i++){
            //动物进入收容所
            if (ope[i][0] == 1){
                if ( ope[i][1] != 0){
                    tempList.add(ope[i][1]);
                }
            }
            //有人想收养动物
            else if (ope[i][0] == 2){
                
                if(ope[i][1] == 0) {
                    resultList.add(tempList.remove(0));
                 }
                 //收养最先进入的狗
                 else if (ope[i][1] == 1){
                     int dog = 0;
                     int index = 0;
                     while(index <tempList.size() ){
                         if(tempList.get(index) > 0){
                             dog = tempList.remove(index);
                             resultList.add(dog); 
                             break;
                         }
                         index++;
                     }
                    
                 }else if (ope[i][1] == -1){ //收养最先进入的猫
                     int cat = 0;
                     int index = 0;
                     while(index <tempList.size() ){
                         if(tempList.get(index) < 0){
                             cat = tempList.remove(index);
                             resultList.add(cat); 
                             break;
                         }
                         index++;
                     }
                    
                 }
            }
        }
        
        return resultList;
    }
}
原文地址:https://www.cnblogs.com/noaman/p/7066241.html