codility icon indicating copy to clipboard operation
codility copied to clipboard

solution2 does not return the correct int if list order is changed

Open alexandrefrigout opened this issue 6 years ago • 0 comments

If the main has the following code System.out.println(solution(new int[] { 7, 9, 3, 9, 3, 9, 9 })); an incorrect number is returned by solution2. The below code for solution2 works well and is of same order:

public static int solution2(int[] A) {
	// write your code in Java SE 8
	HashSet<Integer> dups = new HashSet<Integer>();
	ArrayList<Integer> tmp = new ArrayList<>();
	for (int i = 0; i < A.length; i++) {
		if (dups.add(A[i])) {
			tmp.add(A[i]);
		}
		else{
			tmp.remove(new Integer(A[i]));
		}
	}
	return tmp.get(0);
}

alexandrefrigout avatar May 03 '19 12:05 alexandrefrigout