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

如何检查一个数组(无序)是否包含一个特定的值?这是一个在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 ;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值