牛骨文教育服务平台(让学习变的简单)
博文笔记

在Java中如何高效的判断数组中是否包含某个元素

创建时间:2016-07-18 投稿人: 浏览次数:46928

如何检查一个数组(无序)是否包含一个特定的值?这是一个在Java中经常用到的并且非常有用的操作。同时,这个问题在Stack Overflow中也是一个非常热门的问题。在投票比较高的几个答案中给出了几种不同的方法,但是他们的时间复杂度也是各不相同的。本文将分析几种常见用法及其时间成本。

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

使用List

1 2 3 public static boolean useList(String[] arr, String targetValue) {     return Arrays.asList(arr).contains(targetValue); }

使用Set

1 2 3 4 public static boolean useSet(String[] arr, String targetValue) {     Set<String> set = new HashSet<String>(Arrays.asList(arr));     return set.contains(targetValue); }

使用循环判断

1 2 3 4 5 6 7 public static boolean useLoop(String[] arr, String targetValue) {     for(String s: arr){         if(s.equals(targetValue))             return true;     }     return false; }

使用Arrays.binarySearch()

Arrays.binarySearch()方法只能用于有序数组!!!如果数组无序的话得到的结果就会很奇怪。

查找有序数组中是否包含某个值的用法如下:

1 2 3 4 5 6 7 public static boolean useArraysBinarySearch(String[] arr, String targetValue) {     int a =  Arrays.binarySearch(arr, targetValue);     if(a > 0)         return true;     else         return false; }

时间复杂度

下面的代码可以大概的得出各种方法的时间成本。基本思想就是从数组中查找某个值,数组的大小分别是5、1k、10k。这种方法得到的结果可能并不精确,但是是最简单清晰的方式。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 public static void main(String[] args) {     String[] arr = new String[] {  "CD""BC", "EF", "DE"
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。