您的位置:首页 > 其它

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

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: