We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
import java.util.HashSet; import java.util.Arrays;
public class DuplicateChecker {
public static boolean hasDuplicates(int[] arr) { // Use a HashSet to efficiently detect duplicates. HashSets don't allow duplicates. HashSet<Integer> seen = new HashSet<>(); for (int num : arr) { if (seen.contains(num)) { return true; // Found a duplicate! } seen.add(num); // Add the current number to the set. } return false; // No duplicates found after checking all elements. } public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {1, 2, 3, 2, 5}; int[] arr3 = {1,1,1,1,1}; int[] arr4 = {}; //Empty array System.out.println("Array 1 has duplicates: " + hasDuplicates(arr1)); // Output: false System.out.println("Array 2 has duplicates: " + hasDuplicates(arr2)); // Output: true System.out.println("Array 3 has duplicates: " + hasDuplicates(arr3)); // Output: true System.out.println("Array 4 has duplicates: " + hasDuplicates(arr4)); // Output: false (an empty array has no duplicates) //Demonstrating with other data types (example with Strings): String[] strArr1 = {"apple", "banana", "cherry"}; String[] strArr2 = {"apple", "banana", "apple"}; System.out.println("String Array 1 has duplicates: " + hasDuplicates(strArr1)); // Output: false System.out.println("String Array 2 has duplicates: " + hasDuplicates(strArr2)); // Output: true } //Overloading the hasDuplicates method to work with other data types (e.g., String) public static boolean hasDuplicates(String[] arr) { HashSet<String> seen = new HashSet<>(); for (String str : arr) { if (seen.contains(str)) { return true; } seen.add(str); } return false; }
}
The text was updated successfully, but these errors were encountered:
No branches or pull requests
import java.util.HashSet;
import java.util.Arrays;
public class DuplicateChecker {
}
The text was updated successfully, but these errors were encountered: