We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
Difficulty: 简单
Related Topics: 数组, 哈希表, 分治, 计数, 排序
给定一个大小为 n的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
n
nums
⌊ n/2 ⌋
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:nums = [3,2,3] 输出:3
示例 2:
输入:nums = [2,2,1,1,1,2,2] 输出:2
提示:
n == nums.length
**进阶:**尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
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)] // }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
169. 多数元素
Description
Difficulty: 简单
Related Topics: 数组, 哈希表, 分治, 计数, 排序
给定一个大小为
n
的数组nums
,返回其中的多数元素。多数元素是指在数组中出现次数 大于⌊ n/2 ⌋
的元素。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
示例 2:
提示:
n == nums.length
**进阶:**尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: