Have you ever had to go through a list of numbers and find the ones that are repeated? It can be time-consuming to go through each number one by one and check if it appears more than once. But don't worry, there is an efficient way to do it!
Let's say we have an array of numbers: [2, 4, 5, 2, 6, 7, 5]. We want to find which numbers appear more than once in the array.
One way to do this is by using a HashSet. A HashSet is like a special type of list that only stores unique elements. We can loop through each number in the array and check if it is already in the HashSet. If it is, that means the number is repeated, so we can print it out. If it's not in the HashSet, we can add it to the HashSet so we can check for it later.
Here's an example of the code:
csharpimport java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] arr = {2, 4, 5, 2, 6, 7, 5};
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
if (set.contains(arr[i])) {
System.out.println(arr[i]);
} else {
set.add(arr[i]);
}
}
}
}
When we run this code, we get the output:
2 5
This means that the numbers 2 and 5 appeared more than once in the array.
Using a HashSet is much more efficient than looping through the array multiple times or using nested loops. It has a time complexity of O(N), which means that it takes a linear amount of time to complete.
In conclusion, finding repeated elements in an array can be done efficiently using a HashSet. It saves time and effort by providing a simple and efficient solution to a common problem.