Leet code Majority element Problem :- Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Here is my solution
Approach 1
public static int majorityElement(int[] nums) {
    if (nums.length == 0) {
        return 0;
    }

    Map&lt;Integer, Integer&gt; numCountMap = new HashMap&lt;&gt;();

    int majorityElement = 0;

    for (int i : nums) {
        if (numCountMap.getOrDefault(i, 0) &gt;= nums.length / 2) {
            majorityElement = i;
            break;
        }

        int currentCount = numCountMap.getOrDefault(i, 0);
        numCountMap.put(i, ++currentCount);
    }

    return majorityElement;
}

And here is my approach 2
 public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }

I was thinkin the first approach is better as the complexity would be n in first case and nlogn in 2nd case.
However, the result shows 2nd approach is better.
Please help me understand why 2nd approach is better and any suggestion for code for first and second.
This is not a review, but an extended comment.
Theoretically you are right, a time complexity of the first approach is \$O(n)\$. However, there is also a space complexity, also \$O(n)\$, due to the Map, and the map is a very heavyweight data structure. Even though it promises a constant time access, it is only an amortized constant time, and the constant could be quite large. You must also take into account its cache unfriendlyness.
Meanwhile, both approaches are suboptimal. There is a way to solve the problem in a linear time in constant space.