zoukankan      html  css  js  c++  java
  • 在Java中怎样高效的推断数组中是否包括某个元素

    来自 http://www.hollischuang.com/archives/1269?

    怎样检查一个数组(无序)是否包括一个特定的值?这是一个在Java中经经常使用到的并且非常实用的操作。同一时候,这个问题在Stack Overflow中也是一个非常热门的问题。

    在投票比較高的几个答案中给出了几种不同的方法,可是他们的时间复杂度也是各不相同的。本文将分析几种常见使用方法及其时间成本。

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

    使用List

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

    使用Set

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

    使用循环推断

    public static boolean useLoop(String[] arr, String targetValue) {
        for(String s: arr){
            if(s.equals(targetValue))
                return true;
        }
        return false;
    }
    

    使用Arrays.binarySearch()

    Arrays.binarySearch()方法仅仅能用于有序数组!

    !!

    假设数组无序的话得到的结果就会非常奇怪。

    查找有序数组中是否包括某个值的使用方法例如以下:

    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。

    这样的方法得到的结果可能并不精确。可是是最简单清晰的方式。

    public static void main(String[] args) {
        String[] arr = new String[] {  "CD",  "BC", "EF", "DE", "AB"};
    
        //use list
        long startTime = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            useList(arr, "A");
        }
        long endTime = System.nanoTime();
        long duration = endTime - startTime;
        System.out.println("useList:  " + duration / 1000000);
    
        //use set
        startTime = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            useSet(arr, "A");
        }
        endTime = System.nanoTime();
        duration = endTime - startTime;
        System.out.println("useSet:  " + duration / 1000000);
    
        //use loop
        startTime = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            useLoop(arr, "A");
        }
        endTime = System.nanoTime();
        duration = endTime - startTime;
        System.out.println("useLoop:  " + duration / 1000000);
    
        //use Arrays.binarySearch()
        startTime = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            useArraysBinarySearch(arr, "A");
        }
        endTime = System.nanoTime();
        duration = endTime - startTime;
        System.out.println("useArrayBinary:  " + duration / 1000000);
    }
    

    执行结果:

    useList:  13
    useSet:  72
    useLoop:  5
    useArraysBinarySearch:  9
    使用一个长度为1k的数组
    
    String[] arr = new String[1000];
    
    Random s = new Random();
    for(int i=0; i< 1000; i++){
        arr[i] = String.valueOf(s.nextInt());
    }
    

    结果:

    useList:  112
    useSet:  2055
    useLoop:  99
    useArrayBinary:  12
    

    使用一个长度为10k的数组

    String[] arr = new String[10000];
    
    Random s = new Random();
    for(int i=0; i< 10000; i++){
        arr[i] = String.valueOf(s.nextInt());
    }
    

    结果:

    useList:  1590
    useSet:  23819
    useLoop:  1526
    useArrayBinary:  12
    

    总结

    显然。使用一个简单的循环方法比使用不论什么集合都更加高效。很多开发人员为了方便,都使用第一种方法,可是他的效率也相对较低。由于将数组压入Collection类型中,首先要将数组元素遍历一遍,然后再使用集合类做其它操作。

    假设使用Arrays.binarySearch()方法。数组必须是已排序的。

    由于上面的数组并没有进行排序,所以该方法不可使用。

    实际上,假设你须要借助数组或者集合类高效地检查数组中是否包括特定值,一个已排序的列表或树能够做到时间复杂度为O(log(n)),hashset能够达到O(1)。

    (英文原文结束,以下是译者注)

    使用ArrayUtils

    除了以上几种以外。Apache Commons类库中还提供了一个ArrayUtils类,能够使用其contains方法推断数组和值的关系。

    import org.apache.commons.lang3.ArrayUtils;
    public static boolean useArrayUtils(String[] arr, String targetValue) {
        return ArrayUtils.contains(arr,targetValue);
    }
    

    相同使用以上几种长度的数组进行測试,得出的结果是该方法的效率介于使用集合和使用循环推断之间(有的时候结果甚至比使用循环要理想)。

    useList:  323
    useSet:  3028
    useLoop:  141
    useArrayBinary:  12
    

    useArrayUtils: 181

    useList:  3703
    useSet:  35183
    useLoop:  3218
    useArrayBinary:  14
    useArrayUtils:  3125
    

    事实上,假设查看ArrayUtils.contains的源代码能够发现,他推断一个元素是否包括在数组中事实上也是使用循环推断的方式。

    部分代码例如以下:

        if(array == null) {
            return -1;
        } else {
            if(startIndex < 0) {
                startIndex = 0;
            }
    
            int i;
            if(objectToFind == null) {
                for(i = startIndex; i < array.length; ++i) {
                    if(array[i] == null) {
                        return i;
                    }
                }
            } else if(array.getClass().getComponentType().isInstance(objectToFind)) {
                for(i = startIndex; i < array.length; ++i) {
                    if(objectToFind.equals(array[i])) {
                        return i;
                    }
                }
            }
    
            return -1;
        }
    

    所以,相比較之下,我更倾向于使用ArrayUtils工具类来进行一些合数祖相关的操作。毕竟他能够让我少写非常多代码(由于自己写代码难免有Bug,毕竟apache提供的开源工具类库都是经过无数开发人员考验过的),并且,效率上也并不低太多。

  • 相关阅读:
    redis安装以及php扩展
    Linux下php安装Redis扩展
    正则验证邮箱
    常用方法
    PHPExcel说明
    冒泡排序
    CURL post请求
    PHP生成随机字符串
    PHP中的字符串函数
    PHP中的数组函数
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/7225650.html
Copyright © 2011-2022 走看看