用IntStream生成0到n的流,并找出不在numSet中的数字
给定一个包含 [0, n]
中 n
个数的数组 nums
,找出 [0, n]
这个范围内没有出现在数组中的那个数。
整体思路就是标题说的那样
首先将nums转化为HashSet,这里也可以不一定是HashSet,是ArrayList也可以
Set<Integer> numSet = Arrays.stream(nums)
.boxed()
.collect(Collectors.toSet());
再用IntStream生成0到n的流 IntStream.rangeClosed(0, n) n代表的是nums的长度,并从流中过滤出(就是找到)不在numSet中的数字,num指的是流中的元素
int missingNumber = IntStream.rangeClosed(0, n)
.filter(num -> !numSet.contains(num))
.findFirst()
.orElseThrow(() -> new IllegalStateException("没有找到缺失的数字。"));
巧妙利用stream流,不得不说stream真厉害!
原文地址:https://blog.csdn.net/a486368464/article/details/142793117
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!