Challenges • Asked about 4 years ago by
While testing the solution for the majority element problem, it doesn't seem like given solution works I may be thinking about this incorrectly hence the post:
function majorityElement(nums) {
var temp = nums.sort();
return temp[Math.floor(nums.length/2)];
}
console.log(majorityElement([1,1,3,3,2,4,2,4]));
in the above sample, the given test case will return 3, which is not a majority element? The algorithm goes to a spot in the array where the majority element would be, but depending on the count of elements that may not be the majority element. So for instance, take this array returns 2 as the majority: [1,1,1,3,3,2,4,2,4]. Am I just overthinking a corner case or wrong completely?