fork(2) download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int t = sc.nextInt();
  6. for (; 0 < t; t--) {
  7. int n = sc.nextInt();
  8. int[] tab = new int[n];
  9. for (int i = 0; i < tab.length; i++) {
  10. tab[i] = sc.nextInt();
  11. }
  12. srednia(tab);
  13. }
  14. }
  15.  
  16. private static void srednia(int[] tab) {
  17. int srednia = 0;
  18. int sredniaRszta = 0;
  19. int index;
  20. int indexReszta = 0;
  21.  
  22. for (int i : tab) {
  23. srednia += i;
  24. }
  25.  
  26. if (srednia % tab.length != 0 && srednia % tab.length >= tab.length / 2) {
  27. sredniaRszta = (srednia / tab.length) + 1;
  28. srednia /= tab.length;
  29. } else {
  30. srednia /= tab.length;
  31. }
  32.  
  33. int ilePlus = 0;
  34. int indexPlus = 0;
  35. int sredniaPlus = srednia;
  36. while (sredniaPlus != tab[indexPlus] && sredniaPlus != 0) {
  37. if (indexPlus < tab.length - 1) {
  38. indexPlus++;
  39. } else {
  40. indexPlus = 0;
  41. sredniaPlus++;
  42. }
  43. ilePlus++;
  44. }
  45.  
  46. int ileMinus = 0;
  47. int sredniaMinus = srednia;
  48. int indexMinus = 0;
  49. while (sredniaMinus != tab[indexMinus] && sredniaMinus != 0) {
  50. if (indexMinus < tab.length - 1) {
  51. indexMinus++;
  52. } else {
  53. indexMinus = 0;
  54. sredniaMinus--;
  55. }
  56. ileMinus++;
  57. }
  58.  
  59. if (ilePlus < ileMinus) {
  60. index = indexPlus;
  61. } else {
  62. index = indexMinus;
  63. }
  64.  
  65. while (sredniaRszta != tab[indexReszta] && sredniaRszta != 0) {
  66. if (indexReszta < tab.length - 1) {
  67. indexReszta++;
  68. } else {
  69. indexReszta = 0;
  70. sredniaRszta++;
  71. }
  72. }
  73.  
  74. if (index > indexReszta && sredniaRszta != 0)
  75. System.out.println(tab[indexReszta]);
  76. else
  77. System.out.println(tab[index]);
  78. }
  79.  
  80. private static Scanner sc = new Scanner(System.in);
  81. }
  82.  
  83.  
Success #stdin #stdout 0.08s 2184192KB
stdin
8
5 1 2 3 4 5
6 1 2 3 4 3 1
7 3 1 2 4 5 6 4
7 4 1 2 3 5 6 4
6 1 2 3 4 5 6
6 3 4 1 2 5 6
4 5 16 12 7
4 3 16 14 7
stdout
3
2
3
4
3
3
12
7