标签:
Majority Element II
Given an integer array of size n,
find all elements that appear more than ⌊ n/3 ⌋ times.
The algorithm should run in linear time and in O(1) space.
Hint:
How many majority elements could it possibly have?
Do you have a better hint? Suggest it!
1 /************************************************************************* 2 > File Name: LeetCode229.c 3 > Author: Juntaran 4 > Mail: Juntaranmail@gmail.com 5 > Created Time: Tue 13 May 2016 15:02:25 PM CST 6 ************************************************************************/ 7 8 /************************************************************************* 9 10 Majority Element II 11 12 Given an integer array of size n, 13 find all elements that appear more than ⌊ n/3 ⌋ times. 14 The algorithm should run in linear time and in O(1) space. 15 16 Hint: 17 18 How many majority elements could it possibly have? 19 Do you have a better hint? Suggest it! 20 21 ************************************************************************/ 22 23 #include<stdio.h> 24 25 /** 26 * Return an array of size *returnSize. 27 * Note: The returned array must be malloced, assume caller calls free(). 28 */ 29 30 int* majorityElement(int* nums, int numsSize, int* returnSize) 31 { 32 int firstMajor = 0, count1 = 0, secondMajor = 0, count2 = 0, i = 0; 33 *returnSize = 0; 34 35 for (i = 0; i < numsSize; i++) 36 { 37 if (count1 == 0) firstMajor = nums[i]; 38 else if (count2 == 0 && firstMajor != nums[i]) secondMajor = nums[i]; 39 40 if (nums[i] == firstMajor) 41 count1++; 42 else if (nums[i] == secondMajor) 43 count2++; 44 else 45 count1--, count2--; 46 } 47 count1 = count2 = 0; 48 for (i = 0; i < numsSize; i++) 49 { 50 if (nums[i] == firstMajor) count1++; 51 else if (nums[i] == secondMajor) count2++; 52 } 53 if (count1 > numsSize / 3) 54 (*returnSize)++; 55 else 56 firstMajor = secondMajor; 57 if (count2 > numsSize / 3) 58 (*returnSize)++; 59 60 if (*returnSize == 0) return NULL; 61 int *returnArray = (int *)malloc(sizeof(int) * (*returnSize)); 62 if (returnArray != NULL) 63 { 64 returnArray[0] = firstMajor; 65 if (*returnSize > 1) returnArray[1] = secondMajor; 66 } 67 68 return returnArray; 69 } 70 71 int main() 72 { 73 int nums[] = {2,2,1}; 74 int numsSize = 3; 75 int *returnSize = 0; 76 majorityElement( nums, numsSize, *returnSize); 77 78 return 0; 79 }
标签:
原文地址:http://www.cnblogs.com/Juntaran/p/5511687.html