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. 多数元素 #57

Open
webVueBlog opened this issue Sep 5, 2022 · 0 comments
Open

169. 多数元素 #57

webVueBlog opened this issue Sep 5, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

169. 多数元素

Description

Difficulty: 简单

Related Topics: 数组, 哈希表, 分治, 计数, 排序

给定一个大小为 n的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入:nums = [3,2,3]
输出:3

示例 2:

输入:nums = [2,2,1,1,1,2,2]
输出:2

提示:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

**进阶:**尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    let temp = nums[0]
    let times = 1
    for (let i = 1; i < nums.length; i++) {
        if (nums[i] === temp) {
            times++
        } else {
            times--
            if (times === 0) {
                temp = nums[i + 1]
                times = 1
                i++
            }
        }
    }
    return temp
};

// 排序 
// var majorityElement = function(nums) {
//     nums.sort((a, b) => a - b)
//     return nums[Math.floor(nums.length / 2)]
// }
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