Created
July 14, 2014 02:39
-
-
Save adohe-zz/4c17e6303fe9da36ab97 to your computer and use it in GitHub Desktop.
How to check if an array (unsorted) contains a certain value?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.westudio.java; | |
| import java.util.Arrays; | |
| import java.util.HashSet; | |
| import java.util.Set; | |
| /** | |
| * Actually, if you really need to check if a value is contained in some array/collection efficiently, | |
| * a sorted list or tree can do it in O(log(n)) or hashset can do it in O(1). | |
| */ | |
| public class CheckExists { | |
| private static boolean exists(String[] strings, String str) { | |
| return Arrays.asList(strings).contains(str); | |
| } | |
| private static boolean existsTwo(String[] strings, String str) { | |
| Set<String> set = new HashSet<String>(Arrays.asList(strings)); | |
| return set.contains(str); | |
| } | |
| private static boolean existsThree(String[] strings, String str) { | |
| for (String s: strings) { | |
| if (s.equals(str)) { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| /** | |
| * This method can only be used when the array is sorted | |
| * @param strings | |
| * @param str | |
| * @return | |
| */ | |
| private static boolean existsFour(String[] strings, String str) { | |
| int a = Arrays.binarySearch(strings, str); | |
| if (a < 0) { | |
| return false; | |
| } | |
| return true; | |
| } | |
| public static void main(String[] args) { | |
| String[] strs = {"a", "v", "c", "d", "e"}; | |
| System.out.println(exists(strs, "a")); | |
| System.out.println(existsTwo(strs, "a")); | |
| System.out.println(existsThree(strs, "a")); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment