From 0fb6badcf13657371cc44332f9a6cb123a7259d5 Mon Sep 17 00:00:00 2001 From: MarlzRana <77016115+MarlzRana@users.noreply.github.com> Date: Wed, 25 Oct 2023 11:17:32 +0100 Subject: [PATCH 1/2] Update 0169-majority-element.cpp - The prior solution had a time and space complexity in the 0(n) - The proposed solution has the same time complexity in the O(n) - The proposed solution has an improved space complexity in the O(1) --- cpp/0169-majority-element.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/cpp/0169-majority-element.cpp b/cpp/0169-majority-element.cpp index 8a065624a..81b41ea7d 100644 --- a/cpp/0169-majority-element.cpp +++ b/cpp/0169-majority-element.cpp @@ -7,12 +7,16 @@ The majority element is the element that appears more than ⌊n / 2⌋ times. Yo class Solution { public: int majorityElement(vector& nums) { - unordered_map mp; - int n = nums.size(); - for (int& i : nums){ - if(++mp[i] > n/2) - return i; - } - return -1; + int count{}; + int res{}; + + for (const int& num: nums) { + if (count == 0) { + res = num; + } + count += (num == res) ? 1 : -1; + } + + return res; } }; From b090784ac8a2c89304d9732f5e21c31e9d4f63a4 Mon Sep 17 00:00:00 2001 From: Marlin Ranasinghe <77016115+MarlzRana@users.noreply.github.com> Date: Sun, 29 Oct 2023 17:28:51 +0000 Subject: [PATCH 2/2] Replace zero initialization with zero assignment initialization --- cpp/0169-majority-element.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/0169-majority-element.cpp b/cpp/0169-majority-element.cpp index 81b41ea7d..b8445788e 100644 --- a/cpp/0169-majority-element.cpp +++ b/cpp/0169-majority-element.cpp @@ -7,8 +7,8 @@ The majority element is the element that appears more than ⌊n / 2⌋ times. Yo class Solution { public: int majorityElement(vector& nums) { - int count{}; - int res{}; + int count = 0; + int res = 0; for (const int& num: nums) { if (count == 0) {