如何高效的查询数组中是否包含某个值


一、有四种方式查询数组中是否包含某个值

1、使用List

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

2、使用Set

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

3、使用简单的循环

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

4、使用Arrays.binarySearch(),但这个方法只接受已经排好序的数组

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

二、计算以上四种方式的时间复杂度

1、测试数组的元素个数分别为:5 , 1000, 10000

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); }

Result:

useList:  13 useSet: 72 useLoop: 5 useArraysBinarySearch: 9

Use  a  larger  array(1K):

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

Result:

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

Use  a  larger  array(1K):

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

Result:

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

三、总结

从以上结果可以清晰的看出,使用简单的循环比使用集合更高效,很多开发者更多的使用第一种方式,但是第一种方式并不是最高效的,因为使用集合的时候,需要从数组无序的读取元素,再存储到结合中,这个过程非常耗时;

实际上,一个排序好的List或者Tree时间复杂度仅为:O(log(n)),而HashSet的效率更高:O(1)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM