如何按连续升降序趋势将Integer列表拆分为多个子列表
整数列表按连续升降趋势拆分子列表实现
拆分规则
- 从列表第一个元素开始构建子列表
- 连续元素的升序/降序/相等趋势不变时,持续将元素加入当前子列表
- 趋势发生变化时,以当前子列表的最后一个元素作为新子列表的起始元素,重新构建子列表,直到遍历完成
输入输出示例
示例1
输入:List<Integer> = [1,2,3,4,8,7,5,6]
输出:List<List<Integer>> = [[1,2,3,4,8], [8,7,5], [5,6]]
示例2
输入:List<Integer> = [8,7,8,9]
输出:List<List<Integer>> = [[8,7], [7,8,9]]
示例3
输入:List<Integer> = [1,2,2,1]
输出:List<List<Integer>> = [[1,2], [2,2], [2,1]]
Java 实现代码
import java.util.ArrayList; import java.util.List; public class TrendListSplitter { public static List<List<Integer>> splitByTrend(List<Integer> input) { List<List<Integer>> result = new ArrayList<>(); // 边界情况处理 if (input == null || input.isEmpty()) return result; if (input.size() == 1) { result.add(new ArrayList<>(input)); return result; } List<Integer> currentSub = new ArrayList<>(); currentSub.add(input.get(0)); // 趋势标识:1=升序,0=相等,-1=降序 Integer preTrend = null; for (int i = 1; i < input.size(); i++) { int preVal = input.get(i-1); int curVal = input.get(i); int curTrend = Integer.compare(curVal, preVal); if (preTrend == null) { // 首次计算趋势直接加入当前子列表 preTrend = curTrend; currentSub.add(curVal); } else { if (curTrend == preTrend) { // 趋势不变,追加元素 currentSub.add(curVal); } else { // 趋势变化,保存当前子列表,开启新子列表 result.add(currentSub); currentSub = new ArrayList<>(); currentSub.add(preVal); currentSub.add(curVal); preTrend = curTrend; } } } // 加入最后一个子列表 result.add(currentSub); return result; } public static void main(String[] args) { // 测试示例 System.out.println(splitByTrend(List.of(1,2,3,4,8,7,5,6))); System.out.println(splitByTrend(List.of(8,7,8,9))); System.out.println(splitByTrend(List.of(1,2,2,1))); } }
运行上述代码输出结果和示例完全一致。
内容的提问来源于stack exchange,提问作者user1298426
相关产品推荐
相关产品推荐

