几种检查 数组里是否包含某个值的方法
2014-08-17 14:57
232 查看
一下是几种方法 检查 数组里是否含有某个数值的方法 并给出了时间复杂度
package simpleJava; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Array { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String[] seven = { "ab", "bc", "cd", "de" }; // 用以测时间复杂度 using List long startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useList(seven, "ab"); } long endTime = System.nanoTime(); long duration = endTime - startTime; System.out.println("useList: " + duration / 1000000); startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useSet(seven, "ab"); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("useSet: " + duration / 1000000); startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useLoop(seven, "ab"); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("useLoop: " + duration / 1000000); startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useArraysBinarySearch(seven, "ab"); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("useArraysBinarySearch: " + duration / 1000000); } // using List public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); } // using set public static boolean useSet(String[] arr, String targetValue) { Set<String> set = new HashSet<String>(Arrays.asList(arr)); return set.contains(targetValue); } // using loop public static boolean useLoop(String[] arr, String targetValue) { for (String s : arr) { if (s.equals(targetValue)) return true; } return false; } // using public static boolean useArraysBinarySearch(String[] arr, String targetValue) { int a = Arrays.binarySearch(arr, targetValue); if (a > 0) return true; else return false; } }
相关文章推荐
- 检查数组是否包含某个值的方法
- 无序数组中是否包含某一个要找的元素的几种方法
- 一千零一夜:检查数组包含某一目标元素的几种方法分析
- 《Python CookBook2》 第一章 文本 - 检查字符串中是否包含某字符集合中的字符 && 简化字符串的translate方法的使用
- List的All方法使用问题:我用List1的All方法来确保List1的所有每个数组元素中是否包含Arr1中的任意元素,这个部分很难实现。 因为,没有一个数组中是否包含另一个数组中的任意元素这个功能
- Javascript 检查字符串是否是数字的几种方法
- 用Array.isArray();方法来检查对象是否是数组
- 检查javascript数组中是否包含某元素
- 如何高效检查一个数组中是否包含某个值
- js检查元素是否包含在数组中
- JavaScript判断数组是否包含指定元素的方法
- 【原】检测是否包含特定字符串的几种方法以及性能比较
- jquery几种用来检查checkbox是否选中的方法
- python实现判断数组是否包含指定元素的方法
- 如何高效检查一个数组中是否包含某个值?
- java 检查是否是数组 检查是否是空数组 检查数组是否包含某个元素
- 编写js扩展方法实现判断一个数组中是否包含某个元素
- 编写js扩展方法实现判断一个数组中是否包含某个元素
- jquery几种用来检查checkbox是否选中的方法
- php检查字符串中是否包含7位GSM字符的方法