Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Linux Foundation Training and Certification

Teach Your Child To Read

Disclosure: My content contains affiliate links.

32,304 questions

42,479 answers

573 users

How to find the majority element in a list with Dart

Learn & Practice SQL


59 views
asked Apr 21, 2023 by avibootz
edited Apr 21, 2023 by avibootz

1 Answer

0 votes
// A majority element = element that appears more than size/2 times in an array[size] 

class MyClass
{
    static int getMajorityElement(List<int> lst) {
        List<int> num = List.generate(10,(i_0)=>0,growable: false);
        var  len = lst.length;
      
        for (var  i = 0; i < len; i++) {
            num[lst[i]]++;
        }
        
        for (var i = 0; i < 9; i++) {
            if (num[i] != 0) {
                var val = num[i];  
                print("$i : $val");
                if (num[i] > len / 2) {
                    return i;
                }
            }
        }
        
        return 0;
    }
  
    static void main()
    {
        List<int> lst = [2, 5, 3, 5, 5, 1, 5, 5, 5, 7, 3];
        var  majority = MyClass.getMajorityElement(lst);
      
        if (majority != 0) {
            print("majority element = $majority");
        }
        else {
            print("Majority element doesn\'t exists\n");
        }
    }
}

void main() {
	MyClass.main();
}




/*
run:

1 : 1
2 : 1
3 : 2
5 : 6
majority element = 5


*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Apr 21, 2023 by avibootz
edited Apr 21, 2023 by avibootz

Related questions

2 answers 69 views
2 answers 69 views
1 answer 70 views
1 answer 78 views
...