华为OD机考真题 -书籍长宽度叠放几本

public class BookStacking {
    public static void main(String[] args) {
        String book = "[[20,16],[10,10],[9,10],[15,11],[2,4],[8,9],[3,5],[8,10],[7,10]]";
        //匹配数字
        Pattern pattern = Pattern.compile("\\d+");
        //Pattern pattern = Pattern.compile("[a-zA-Z]+"); 匹配字母
        //Pattern pattern = Pattern.compile("\\D+"); 匹配非数字
        Matcher matcher = pattern.matcher(book);
        String [] size = book.split(",");
        int [][] value = new int[size.length/2][2];
        int i = 0;
        int j = 0;
        //将数字转化为List存储
        while(matcher.find()){
            String match = matcher.group();
            Integer integer = Integer.valueOf(match);
            value[i][j] = integer;
            if (matcher.find()){
                String match2 = matcher.group();
                Integer integer2 = Integer.valueOf(match2);
                j++;
                value[i][j] = integer2;
                j = 0;
            }
            i++;
        }
        //排序
        Comparator<int[]>comparator = (a1,a2)-> Integer.compare(a2[0],a1[0]);
        Arrays.sort(value,comparator);
        //比较书本长宽大小
        int count = 1;
        int num1 = value[0][0];
        int num2 = value[0][1];
        for (int k = 0; k < value.length - 1 ; k++){
            if (num1 > value[k+1][0] && num2 > value[k+1][1]){
                count++;
                num1 =  value[k+1][0];
                num2 = value[k+1][1];
            }
        }
        System.out.println(count);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42450130/article/details/131433375