检查数组是否包含某个值的方法

检查数组是否包含某个值的方法
使用List
publicstaticbooleanreturn Arrays.asList(arr).contains(targetValue); }
使用Set
publicstaticsetnew HashSet<String>(Arrays.asList(arr)); returnset.contains(targetValue); }
使用循环判断
publicstaticbooleanforifreturntrue; } returnfalse; }
使用 Arrays.binarySearch()
publicstaticbooleanint a = Arrays.binarySearch(arr, targetValue); if0returntrue; elsereturnfalse; }
时间复杂度
publicstaticvoidnew"CD""BC""EF""DE""AB"}; //use listlong startTime = System.nanoTime(); forint0100000; i++) { useList(arr, ); } long endTime = System.nanoTime(); long duration = endTime - startTime; System.out"useList: "1000000); //use set startTime = System.nanoTime(); forint0100000; i++) { useSet(arr, ); } endTime = System.nanoTime(); duration = endTime - startTime; System.out"useSet: "1000000); //use loop startTime = System.nanoTime(); forint0100000; i++) { useLoop(arr, ); } endTime = System.nanoTime(); duration = endTime - startTime; System.out"useLoop: "1000000); //use Arrays.binarySearch() startTime = System.nanoTime(); forint0100000; i++) { useArraysBinarySearch(arr, ); } endTime = System.nanoTime(); duration = endTime - startTime; System.out"useArrayBinary: "1000000); }
: : : :
使用一个长度为1k的数组
new1000]; Random s = new Random(); forint01000; i++){ arr[i] = String.valueOf(s.nextInt()); }
: : : :
使用一个长度为10k的数组
new10000]; Random s = new Random(); forint010000; i++){ arr[i] = String.valueOf(s.nextInt()); }
: : : :
 
总结
Arrays.binarySearch()使用 ArrayUtils
ArrayUtilscontainsimport org.apache.commons.lang3.ArrayUtils; publicstaticbooleanreturn ArrayUtils.contains(arr,targetValue); }
posted @   对我有点小自信  阅读(650)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示