Share my solution using sort function in STL as follows:


  • 0
    Y
    class Solution {
    public:
    	int majorityElement(vector<int> &num) {
    		int  majoritynum = static_cast<int>(floor(num.size() / 2.0));
    		sort(num.begin(), num.end());
    		for (int i = 0, cur = num[0], total = 0; i < num.size(); i++) {
    			if (num[i] == cur)
    				total++;
    			else {
    				cur = num[i];
    				total = 1;
    			}
    
    			if (total > majoritynum)
    				return cur;
    		}
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.