DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Majority Element -I

const majorityElement_1 = (arr) => {
  let map = new Map();
  let maxOcuuredElement = -1;
  let comparedTo = Math.floor(arr.length / 2);

  for (let i = 0; i < arr.length; i++) {
    if (!map.has(arr[i])) {
      map.set(arr[i], 1);
    } else {
      map.set(arr[i], map.get(arr[i]) + 1);
    }
  }

  for (let [key, value] of map) {
    console.log(key + " = " + value);
    if (value > comparedTo) {
      maxOcuuredElement = key;
    }
  }
  return maxOcuuredElement;
};

// console.log(removeExactlyOneDuplicate([2, 3, 9, 2, 2]));
// console.log(removeExactlyOneDuplicate([8, 5, 1, 9]));
console.log(removeExactlyOneDuplicate([2, 2, 3, 3]));

var majorityElement = function (nums) {
  let map = {};

  for (let i = 0; i < nums.length; i++) {
    if (map[nums[i]]) {
      map[nums[i]] = map[nums[i]] + 1;
    } else {
      map[nums[i]] = 1;
    }
  }

  let max = 0;
  let maxKey = 0;
  for (const key in map) {
    let value = map[key];
    if (max < value) {
      max = value;
      maxKey = key;
    }
  }
  return maxKey;
};


Enter fullscreen mode Exit fullscreen mode

Top comments (0)