Find the majority element in array

Использование:

using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();

myList.Sort(
    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
);

, Так как Вы нацелены на.NET 2.0 или выше, можно упростить это в синтаксис лямбды - это эквивалентно, но короче. При предназначении для.NET 2.0, можно только использовать этот синтаксис при использовании компилятора от Visual  Studio  2008 (или выше).

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
51
задан xenteros 2 August 2017 в 23:32
поделиться

1 ответ

public class MajorityElement {

   public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int testCases = sc.nextInt();
    while(testCases-- > 0) {
        int n = sc.nextInt();
        int a[] = new int[n];
        int maxCount = 0;
        int index = -1;
        for(int i = 0 ; i < n; i++) {
            a[i] = sc.nextInt();
        }
        for(int i = 0; i < n; i++) {
            int count =0;
            for(int j = 0; j < n; j++) {
                if(a[i] == a[j])
                    count++;
            }
            if(count > maxCount) {
                maxCount = count;
                index = i;
            }
        }
        if(maxCount > n/2)
            System.out.println(a[index]);
        else
            System.out.println(-1);
    }
    sc.close();
   }

}
0
ответ дан 7 November 2019 в 09:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: