(Coderbyte) Second GreatLow - Solução

Have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space. For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will contain at least 2 numbers. It can get tricky if there's just two numbers!

Solução:

import java.util.*;
import java.io.*;

class Function {
  String SecondGreatLow(int[] arr) {
    // o Set é uma coleção de objetos únicos
    // ao adicionar elementos repetidos, o Set automaticamente irá desconsiderá-los
    Set<Integer> set = new HashSet<>();
    for(int a: arr) {
      set.add(a);
      }
    Integer[] novo = set.toArray(new Integer[set.size()]);
  
    Arrays.sort(novo);

    if (novo.length == 1) {
        return novo[0]+" "+novo[0];
    }

    return novo[1]+" "+novo[novo.length-2];    
  }
 
  public static void main (String[] args) {
    // keep this function call here   
    Scanner  s = new Scanner(System.in);
    Function c = new Function();
    System.out.print(c.SecondGreatLow(s.nextLine()));
  } 
 
}   

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução