import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ContainsDuplicate {
@Test
public void test() {
int[] a = {1, 2, 3, 1};
assertTrue(containsDuplicateWithSet(a));
assertTrue(containsDuplicateWithSort(a));
assertTrue(containsDuplicateWithStream(a));
int[] b = {1, 2, 3, 4};
assertFalse(containsDuplicateWithSet(b));
assertFalse(containsDuplicateWithSort(b));
assertFalse(containsDuplicateWithStream(b));
int[] c = {1, 1, 1, 3, 3, 4, 3, 2, 4, 2};
assertTrue(containsDuplicateWithSet(c));
assertTrue(containsDuplicateWithSort(c));
assertTrue(containsDuplicateWithStream(c));
}
public boolean containsDuplicateWithSet(int[] array) {
Set<Integer> set = new HashSet<>();
for (int num : array) {
if (!set.add(num)) {
return true;
}
}
return false;
}
public boolean containsDuplicateWithSort(int[] array) {
Arrays.sort(array);
for (int i = 1; i < array.length; i++) {
if (array[i - 1] == array[i]) {
return true;
}
}
return false;
}
public boolean containsDuplicateWithStream(int[] array){
return Arrays.stream(array).distinct().count()!=array.length;
}
}
No comments:
Post a Comment