I am trying to solve this problem in which we have an array in which some elements are unique, and some are repetitive. For example, int[] array = { 4, 4, 6, 1, 2, 3, 5, 5 };
.
So, the second largest non-repeating number would be 3. My output is coming as 2. The code isL
public class SecondLargestNonRepeatingNumber {
public static void main(String[] args) {
int[] array = { 4, 4, 6, 1, 2, 3, 5, 5 };
System.out.println(process(array));
}
public static int process(int[] array) {
int counter2 = 0;
int result = 0;
Arrays.sort(array);
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int count = array.length;
int index = 0;
while(count>0) {
if(map.containsKey(array[index])) {
map.put(array[index], map.get(array[index])+1);
}else {
map.put(array[index], 1);
}
index++;
count--;
}
int maxNum = Integer.MIN_VALUE;
// for (int i = 0; i < array.length; i++) {
// for (int j = i + 1; j < array.length; j++) {
// if (array[i] != array[j] && array[i] > maxNum) {
// maxNum = array[i];
// counter2++;
// }
// if (counter2 == 2)
// break;
// }
// }
for(Map.Entry<Integer,Integer> entry:map.entrySet()) {
if(entry.getValue()==1) {
if(entry.getKey() > maxNum) {
maxNum = entry.getKey();
}
counter2++;
}
if(counter2==2) {
result = entry.getKey();
}
}
return result;
}
}