Home > OS >  Second Largest Non Repeating Number in an Array
Second Largest Non Repeating Number in an Array

Time:04-07

I am trying to solve this problem in which we have an array in which some elements are unique, and some are repetitive. Like for e.g. 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 is -

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;
    }

}

Thanks in advance.

CodePudding user response:

Sorry, but now when I tried it again, I found this solution that is working -

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;
//          }
//      }
        List<Integer> list = new ArrayList<Integer>();
        
    for(Map.Entry<Integer,Integer> entry:map.entrySet()) {
        if(entry.getValue()==1) {
            
                list.add(entry.getKey());
            
            counter2  ;
        }
        Collections.sort(list);
    }

        return list.get(list.size()-2);
    }

}

CodePudding user response:

Instead of using a standard HashMap and then sorting you could instead use a TreeMap that maintains sorted order of the keys for you:

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class SecondLargestNonRepeatingNumber {
    public static void main(String[] args) {
        int[] array = { 4, 4, 6, 1, 2, 3, 5, 5 };
        System.out.println(Arrays.toString(array));
        System.out.printf("Second largest non repeating number: %d%n",
            getSecondLargestNonRepeatingNumber(array));
    }

    public static int getSecondLargestNonRepeatingNumber(int[] array) {
        Map<Integer, Integer> counts = new TreeMap<>();
        for (int x : array) {
            counts.put(x, counts.getOrDefault(x, 0)   1);
        }
        counts.entrySet().stream()
            .filter(e -> !e.getValue().equals(1))
            .map(Entry::getKey)
            .collect(Collectors.toList())
            .forEach(counts.keySet()::remove);
        return counts.keySet().stream().skip(1).findFirst()
            .orElseThrow(); // When there is less than 2 unique numbers in array.
    }
}

Output:

[4, 4, 6, 1, 2, 3, 5, 5]
Second largest non repeating number: 2
  • Related