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

来源:互联网 发布:网络博客被黑客攻击 编辑:程序博客网 时间:2024/06/03 07:36

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

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

使用List

1
2
3
public static boolean useList(String[] arr, String targetValue) {
    returnArrays.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));
    returnset.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))
            returntrue;
    }
    returnfalse;
}

使用Arrays.binarySearch()

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

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

1
2
3
4
5
6
7
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
    inta =  Arrays.binarySearch(arr, targetValue);
    if(a >0)
        returntrue;
    else
        returnfalse;
阅读全文
0 0
原创粉丝点击