如何判断Java中变长嵌套List是否按索引递增有序
判断嵌套
List<List<Integer>>的索引顺序有效性 我需要处理一个包含任意数量变长List<Integer>的List<List<Integer>>,要求按索引逐一比较各子List对应位置的值,判断整个嵌套List是否按从小到大的顺序排列。
示例说明
错误顺序示例1
List<List<Integer>> listOfLists = List.of(List.of(5, 3, 2), // A List.of(5, 3), // B List.of(5, 3)); // C
索引0和1处值均相同,索引2处listA有值而B、C无,因此顺序错误,应返回false。
错误顺序示例2
List<List<Integer>> listOfLists = List.of(List.of(4, 3, 2, 1), // A List.of(4, 3, 2), // B List.of(4, 3, 2, 1)); // C
listB在最后索引处无值,小于A、C的对应值,顺序错误,返回false。
正确顺序示例
List<List<Integer>> listOfLists = List.of(List.of(4, 3), // A List.of(4, 3, 1), // B List.of(5, 3, 2, 1), // C List.of(5, 4, 3)); // D
各索引位置值均按从小到大排列,返回true。
尝试过程
我曾尝试使用Comparator自定义比较方法、嵌套循环、递归等方案,但频繁遇到IndexOutOfBOundsException;虽能实现子List排序或找最大值,但无法完成原顺序的有效性判断。我考虑过将同索引值入栈比较,但实现存在困难。
可行实现代码
public class ListTest { public static void main(String... args) { List<List<Integer>> listOfLists = List.of(List.of(3, 2, 1), // A List.of(4, 3, 1), // B List.of(5, 4, 3)); // C boolean correctOrder = true; int max = getMaxLength(listOfLists); Stack<Integer> stack = new Stack<>(); for (int i = 0; i < max; i++) { for (int j = 0; j < listOfLists.size(); j++) { try { stack.push(listOfLists.get(j).get(i)); } catch(IndexOutOfBoundsException ex) { stack.push(0); } } if (!isSorted(stack)) { correctOrder = false; break; } } System.out.println(correctOrder); } public static boolean isSorted(Stack<Integer> stack) { int temp = stack.pop(); while (!stack.isEmpty()) { int compare = stack.pop(); if (temp < compare) return false; temp = compare; } return true; } public static int getMaxLength(List<List<Integer>> list) { int maxLength = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i).size() > maxLength) { maxLength = list.get(i).size(); System.out.println(maxLength); } } return maxLength; } }
内容的提问来源于stack exchange,提问作者thelinuxfan
相关产品推荐
相关产品推荐

