Last active
March 31, 2017 16:05
-
-
Save lovasoa/32591962065ac627200968e7096be249 to your computer and use it in GitHub Desktop.
Дан целочисленный массив из 1001 элемента , все числа в массиве имеют пару и одно уникальное. найдите это число за O(n).
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
import java.util.*; | |
/* | |
Дан целочисленный массив из 1001 элемента , | |
все числа в массиве имеют пару и одно уникальное. | |
найдите это число за O(n). | |
*/ | |
class NotInPair { | |
public static <E> E not_in_pair(Iterable<E> elements) { | |
Set<E> uniques = new HashSet<>(); | |
for(E element : elements) { | |
if (uniques.contains(element)) uniques.remove(element); | |
else uniques.add(element); | |
} | |
if (uniques.size() == 1) return uniques.iterator().next(); | |
else throw new IllegalArgumentException("No unique single element"); | |
} | |
public static void main(String[] args) { | |
ArrayList<Integer> numbers = new ArrayList<>(); | |
for(int i=1; i<=1001; i++) numbers.add(i % 501); | |
System.out.println("Массив: " + numbers); | |
System.out.println("Уникальное число: " + not_in_pair(numbers)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment