diff --git a/Medium/Readme.md b/Medium/Readme.md new file mode 100644 index 0000000..0d84f28 --- /dev/null +++ b/Medium/Readme.md @@ -0,0 +1,19 @@ +Problem #229 (Majority Element II | Array, Counting, Hash Table, Sorting) +Medium + +Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. + +Example 1 +Input: nums = [3,2,3] **Output:** [3]` + +Example 2: +Input: nums = [1] +Output: [1] + +Example 3: +Input: nums = [1,2] +Output: [1,2] + +Constraints: +. 1<=nums.length<= 5*104 +. -109<=nums[i]<=10^9 \ No newline at end of file diff --git a/Medium/solution.cpp b/Medium/solution.cpp new file mode 100644 index 0000000..3c811fa --- /dev/null +++ b/Medium/solution.cpp @@ -0,0 +1,35 @@ +class Solution { + public: + vector majorityElement(vector& nums) { + vector ans; + int candidate1 = 0; + int candidate2 = 1; // Any number different from candidate1 + int countSoFar1 = 0; // # of candidate1 so far + int countSoFar2 = 0; // # of candidate2 so far + + for (const int num : nums) + if (num == candidate1) { + ++countSoFar1; + } else if (num == candidate2) { + ++countSoFar2; + } else if (countSoFar1 == 0) { // Assign new candidate + candidate1 = num; + ++countSoFar1; + } else if (countSoFar2 == 0) { // Assign new candidate + candidate2 = num; + ++countSoFar2; + } else { // Meet a new number, so pair out previous counts + --countSoFar1; + --countSoFar2; + } + + const int count1 = count(nums.begin(), nums.end(), candidate1); + const int count2 = count(nums.begin(), nums.end(), candidate2); + + if (count1 > nums.size() / 3) + ans.push_back(candidate1); + if (count2 > nums.size() / 3) + ans.push_back(candidate2); + return ans; + } +}; diff --git a/Medium/solution.java b/Medium/solution.java new file mode 100644 index 0000000..4a034d6 --- /dev/null +++ b/Medium/solution.java @@ -0,0 +1,40 @@ +class Solution { + public List majorityElement(int[] nums) { + List ans = new ArrayList<>(); + int candidate1 = 0; + int candidate2 = 1; // Any number different from candidate1 + int countSoFar1 = 0; // # of candidate1 so far + int countSoFar2 = 0; // # of candidate2 so far + + for (final int num : nums) + if (num == candidate1) { + ++countSoFar1; + } else if (num == candidate2) { + ++countSoFar2; + } else if (countSoFar1 == 0) { // Assign new candidate + candidate1 = num; + ++countSoFar1; + } else if (countSoFar2 == 0) { // Assign new candidate + candidate2 = num; + ++countSoFar2; + } else { // Meet a new number, so pair out previous counts + --countSoFar1; + --countSoFar2; + } + + int count1 = 0; + int count2 = 0; + + for (final int num : nums) + if (num == candidate1) + ++count1; + else if (num == candidate2) + ++count2; + + if (count1 > nums.length / 3) + ans.add(candidate1); + if (count2 > nums.length / 3) + ans.add(candidate2); + return ans; + } +}