Your code only looks at the previous value to determine to add a value which means that your code will only work if all the values are in the contiguous array like this:
{1,1,2,2}
To make your code work, you need to record all the elements that you have seen before, not just the ones at the start of the previous run. You can do this:
LinkedHashSet<Integer> set=new LinkedHashSet<>(Arrays.asList(arr));
Or
set.addAll(Arrays.asList(arr));
If you want to return an int array you need to copy the elements back into an array:
int[] result = new int[set.size()];
int index = 0;
for (int value : set)
{
result[index++] = value;
}
return result;
Want to learn Java? Check out the Java certification from Intellipaat.