欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > LeetCode //C - 229. Majority Element II

LeetCode //C - 229. Majority Element II

2024/10/24 7:27:23 来源:https://blog.csdn.net/navicheung/article/details/140454876  浏览:    关键词:LeetCode //C - 229. Majority Element II

229. Majority Element II

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 < = n u m s . l e n g t h < = 5 ∗ 1 0 4 1 <= nums.length <= 5 * 10^4 1<=nums.length<=5104
  • − 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 109<=nums[i]<=109

From: LeetCode
Link: 229. Majority Element II


Solution:

Ideas:
  1. Initialization: We initialize two candidates with any two different values and their counts to 0. This ensures that our algorithm doesn’t falsely initialize both candidates to the same value.

  2. First Pass: We iterate through the array to find up to two potential candidates for the majority elements.

  • If the current element matches one of the candidates, we increment its count.
  • If the current element does not match either candidate and one of the counts is zero, we update that candidate and reset its count.
  • If the current element does not match either candidate and both counts are non-zero, we decrement both counts.
  1. Second Pass: We verify if the candidates we found in the first pass actually appear more than ⌊n/3⌋ times.
  2. Result Construction: We construct the result array with the verified candidates.
Code:
/*** Note: The returned array must be malloced, assume caller calls free().*/
int* majorityElement(int* nums, int numsSize, int* returnSize) {if (numsSize == 0) {*returnSize = 0;return NULL;}int candidate1 = 0, candidate2 = 1; // Initialize candidates to any two different valuesint count1 = 0, count2 = 0;// 1st pass: find potential candidatesfor (int i = 0; i < numsSize; i++) {if (nums[i] == candidate1) {count1++;} else if (nums[i] == candidate2) {count2++;} else if (count1 == 0) {candidate1 = nums[i];count1 = 1;} else if (count2 == 0) {candidate2 = nums[i];count2 = 1;} else {count1--;count2--;}}// 2nd pass: verify candidatescount1 = 0;count2 = 0;for (int i = 0; i < numsSize; i++) {if (nums[i] == candidate1) {count1++;} else if (nums[i] == candidate2) {count2++;}}int* result = (int*)malloc(2 * sizeof(int));*returnSize = 0;if (count1 > numsSize / 3) {result[*returnSize] = candidate1;(*returnSize)++;}if (count2 > numsSize / 3) {result[*returnSize] = candidate2;(*returnSize)++;}return result;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com