169. Majority Elements

202405261412
tags: #divide-and-conquery

var majorityElement = function(nums) {
	const getMajorElement = (start, end) => {
		if (start >= end) {
			return nums[start];
		}
		const mid = Math.floor((end - start) / 2) + start;
		const leftMajorElement = getMajorElement(start, mid);
		const rightMajorElement = getMajorElement(mid + 1, end);
		if (leftMajorElement === rightMajorElement) {
			return leftMajorElement;
		}
		let leftMajorCounts = 0;
		let rightMajorCounts = 0;
		for (let i = start; i <= end; i++) {
			if (nums[i] === leftMajorElement) {
				leftMajorCounts += 1;
			}
			else if (nums[i] === rightMajorElement) {
				rightMajorCounts += 1;
			}
		}
		return leftMajorCounts > rightMajorCounts ? leftMajorElement : rightMajorElement;
	}
	return getMajorElement(0, nums.length - 1);
};

Reference

https://www.youtube.com/watch?v=mVpH8byx51Y