Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

169. Majority Element #9

Open
soonlive opened this issue Nov 1, 2016 · 0 comments
Open

169. Majority Element #9

soonlive opened this issue Nov 1, 2016 · 0 comments

Comments

@soonlive
Copy link
Owner

soonlive commented Nov 1, 2016

169. Majority Element

image

  /**
   * @param {number[]} nums
   * @return {number}
   */
  var majorityElement = function (nums) {
    return majority(nums, 0, nums.length - 1);
  };

  function majority(nums, left, right) {
    if (left === right) {
      return nums[left];
    }
    var mid = left + ((right - left) >> 1);
    var lm = majority(nums, left, mid);
    var rm = majority(nums, mid + 1, right);
    if (lm === rm) {
      return lm;
    }

    var lcount = 0;
    var rcount = 0;
    nums.slice(left, right + 1).forEach(function (n) {
      if (lm === n) {
        ++lcount;
      }
      if (rm === n) {
        ++rcount;
      }
    });
    return lcount > rcount ? lm : rm;
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant