HZFE / algorithms-solving

1 stars 0 forks source link

2022-08-11 #13

Open github-actions[bot] opened 2 years ago

gongpeione commented 2 years ago

169 Majority Element

/*
 * @lc app=leetcode id=169 lang=typescript
 *
 * [169] Majority Element
 */

// @lc code=start
function majorityElement(nums: number[]): number {
    // const numCounter = {};
    // for (let i = 0; i < nums.length; i++) {
    //     const n = nums[i];
    //     if (!numCounter[n]) {
    //         numCounter[n] = 1;
    //     }
    //     if (numCounter[n] > nums.length / 2) {
    //         return n;
    //     }
    //     numCounter[n]++;
    // }

    let counter = 0;
    let target = 0;
    // if the size of the target number greater than n / 2
    // then it will last till then end
    for (let i = 0; i < nums.length; i++) {
        const n = nums[i];
        if (counter === 0) {
            target = n;
        }
        if (n === target) {
            counter++;
        } else {
            counter--;
        }
    }

    return target;
};
// @lc code=end

Nickname: Geeku From vscode-hzfe-algorithms

Akiq2016 commented 2 years ago
// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function (nums) {
  if (nums.length === 1) return nums[0];

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

    if (count == -1) {
      majority = nums[i];
      count = 0;
    }
  }

  return majority;
};
// @lc code=end