如何高效地判断数组中是否包含某特定值



如何检查一个未排序的数组中是否包含某个特定值,这是一个在Java中非常实用并且频繁使用的操作。另外,这也是Stack Overflow上面非常受关注的问题。在得票数最多的答案中,可以看到,检查数组中是否包含特定值可以用多种不同的方式实现,但是时间复杂度差别很大。下面,我将为大家展示各种方法及其需要花费的时间。

1.检查数组中是否包含特定值的四种不同方法

1)使用List:

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

2)使用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);
}

3)使用一个简单循环:

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

4)使用Arrays.binarySearch():

注:下面的代码是错误的,这样写出来仅仅为了理解方便。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 ;
}

2.时间复杂度

通过下面的这段代码可以近似比较几个方法的时间复杂度。虽然分别搜索一个大小为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" , "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 );
}

结果:

1
2
3
4
useList:  13
useSet:  72
useLoop:  5
useArraysBinarySearch:  9

对于长度为1K的数组:

1
2
3
4
5
6
String[] arr = new String[ 1000 ];
  
Random s = new Random();
for ( int i= 0 ; i< 1000 ; i++){
     arr[i] = String.valueOf(s.nextInt());
}

结果:

1
2
3
4
useList:  112
useSet:  2055
useLoop:  99
useArrayBinary:  12

对于长度为10K的数组:

1
2
3
4
5
6
String[] arr = new String[ 10000 ];
  
Random s = new Random();
for ( int i= 0 ; i< 10000 ; i++){
     arr[i] = String.valueOf(s.nextInt());
}

结果:

1
2
3
4
useList:  1590
useSet:  23819
useLoop:  1526
useArrayBinary:  12

很明显,使用简单循环的方法比使用其他任何集合效率更高。许多开发者会使用第一种方法,但是它并不是高效的。将数组压入Collection类型中,需要首先将数组元素遍历一遍,然后再使用集合类做其他操作。

如果使用Arrays.binarySearch()方法,数组必须是已排序的。由于上面的数组并没有进行排序,所以该方法不可使用。

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

原文链接: programcreek 翻译: ImportNew.com 0x0bject

### Vue 中判断数组是否包含特定方法 在 Vue.js 开发过程中,经常需要判断一个数组是否包含某个特定。以下是几种常用的方法及其具体实现: #### 方法一:`find()` `some()` `find()` 方法用于返回数组中第一个满足条件的元素;而 `some()` 方法则用来检测是否有至少一个元素满足给定条件。 ```javascript let arr = [{ name: 'ZS' }, { name: 'WW' }, { name: 'LS' }]; // 使用 find() if (arr.find(item => item.name === 'WW')) { console.log('存在'); } else { console.log('不存在'); } // 使用 some() if (arr.some(item => item.name === 'WW')) { console.log('存在'); } else { console.log('不存在'); } ``` 这两种方法都可以高效地完成目标[^1]。 --- #### 方法二:`indexOf()` `includes()` 对于简单的数或字符串类型的数组,可以使用 `indexOf()` 或者 ES6 提供的新方法 `includes()` 来快速判断。 ```javascript let simpleArray = ['apple', 'banana', 'orange']; // 使用 indexOf() if (simpleArray.indexOf('banana') !== -1) { console.log('存在'); } else { console.log('不存在'); } // 使用 includes() if (simpleArray.includes('banana')) { console.log('存在'); } else { console.log('不存在'); } ``` 需要注意的是,`indexOf()` 对于复杂对象可能无法正常工作,因为它比较的是引用地址而非实际内容[^2]。 --- #### 方法三:`filter()` 进行筛选 虽然 `filter()` 主要用于过滤出符合条件的所有项,但它也可以间接帮助我们判断是否存在某些。 ```javascript let complexArray = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]; let result = complexArray.filter(item => item.id === 2); if (result.length > 0) { console.log('存在'); } else { console.log('不存在'); } ``` 这种方法适用于需要进一步处理匹配结果的情况[^3]。 --- #### 殊情况下的注意事项 当涉及到虚拟 DOM 更新时,Vue 内部会调用类似于 `sameVnode` 的逻辑来判断节点的一致性。这通常不涉及普通的数组查找场景,但在自定义渲染函数或者递归组件时可能会遇到类似的原理[^4]。 --- ### 总结 以上介绍了多种方式来解决 Vue 中关于数组是否包含的问题。开发者可以根据实际情况选择最适合当前需求的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值