AlgoDaily Solution

1var assert = require('assert');
2
3/**
4 * @param {number[]} nums
5 * @return {number}
6 */
7function majorityElement(nums) {
8  var sortedNums = nums.sort();
9  return sortedNums[Math.floor(nums.length / 2)];
10}
11
12// console.log(majorityElement([1, 1, 1, 4, 2, 4, 4, 3, 1, 1, 1]));
13
14try {
15  assertIsFunction(majorityElement, '`majorityElement` is a function');
16
17  console.log('PASSED: ' + '`majorityElement` is a function');
18} catch (err) {
19  console.log(err);
20}
21
22try {
23  assert.equal(majorityElement([1, 4, 2, 4, 4, 3, 4]), 4);
24
25  console.log(
26    'PASSED: ' + '`majorityElement([1, 4, 2, 4, 4, 3, 4])` should return `4`'
27  );
28} catch (err) {
29  console.log(err);
30}
31
32try {
33  assert.equal(majorityElement([1, 1, 1, 4, 2, 4, 4, 3, 1, 1, 1]), 1);
34
35  console.log(
36    'PASSED: `majorityElement([1, 1, 1, 4, 2, 4, 4, 3, 1, 1, 1])` should return `1`'
37  );
38} catch (err) {
39  console.log(err);
40}
41
42function assertIsFunction(f) {
43  return typeof f === 'function';
44}

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.