如何判断list是否递增且是连续的
public static boolean isContinuous1(List<Integer> nums) {
AtomicBoolean continuous = new AtomicBoolean(true);
AtomicInteger counter = new AtomicInteger(nums.get(0));
nums.forEach(item -> {
if (counter.getAndIncrement() != item) {
continuous.set(false);
}
});
return continuous.get();
}
还有更优雅的写法吗
可以借助lambda
public static boolean isContinuous2(List<Integer> nums) {
AtomicInteger counter = new AtomicInteger(nums.get(0));
return nums.stream().allMatch(i -> i == counter.getAndIncrement());
}
跑一波单测
public static void main(String[] args) {
List<Integer> nums = ImmutableList.of(2, 3, 4, 5, 6);
System.out.println(isContinuous1(nums));
System.out.println(isContinuous2(nums));
List<Integer> nums1 = ImmutableList.of(2, 3, 4, 5, 6, 9, 10);
System.out.println(isContinuous1(nums1));
System.out.println(isContinuous2(nums1));
}
输出:
true
true
false
false
如果是递增但不连续呢,如果是递减且不连续还包括负数呢
如果是按照一定规则递增呢,比如n的平方
说点什么
2 评论 在 "每周一练(34)"
可以给方法参数额外传个函数式接口,方法调用时,根据判断条件(递增,平方递增)等来做不同的实现,算是比较优雅 ^_^
可以啊,贴下面