Majority Element

Given an array nums of size n, return the majority element.
The majority element is the element that appears more than [n/2] times. You may assume that the majority element always exists in the array.

Example 1:

Input: nums ={3,2,3}
Output: 3

Approach

Java

import java.util.Arrays;

public class MajorityElement {
    public static void main(String[] args) {
        int[] nums = { 323 };
        System.out.println(majorityElement(nums));
    }

    static int majorityElement(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        return nums[n / 2];
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int majorityElement(vector<int>& nums
{
     sort(nums.begin(),nums.end());
      int n=nums.size();
     return nums[n/2];
}

int main()
{
    vector<intnums ={3,2,3};
    cout<<majorityElement(nums);
    return 0;
}




No comments:

Post a Comment