题目大意:找到个数大于总数三分之一的主元素,O(n)时间复杂度,O(1)空间复杂度。
有几种不同的返回情况:
可能没有主元素,可能有一个,可能有两个。
像之前的主元素题目一样,要用临时变量来抵消不同的元素,不过不同的是,一个新元素需要抵消两个已有的元素,因为非主元素的个数不会超过总数的1/3,因此最终不会被抵消完。
AC 代码:(C语言)
int* majorityElement(int* nums, int numsSize, int* returnSize) {
int *res = NULL;
int n1 = 0, c1 = 0;
int n2 = 0, c2 = 0;
int i = 0, t = 0;
int flag = 0;
if(1 == numsSize) {
*returnSize = 1;
res = (int*)malloc(sizeof(int));
res[0] = nums[0];
return res;
}
else if(0 == numsSize){
*returnSize = 0;
res = (int*)malloc(0);
return res;
}
n1 = nums[0];
c1 = 1;
n2 = 0;
c2 = 0;
for (i = 1; i < numsSize; ++i) {
t = nums[i];
if (t == n1) ++c1;
else if (t == n2) ++c2;
else if (0 == c1) n1 = t, c1 = 1;
else if (0 == c2) n2 = t, c2 = 1;
else --c1, --c2;
}
c1 = 0;
c2 = 0;
*returnSize= 0;
for (i = numsSize - 1; i >= 0; --i) {
if (nums[i] == n1) ++c1;
else if (nums[i] == n2) ++c2;
}
if(c1 > numsSize / 3) {
*returnSize = *returnSize + 1;
flag |= 1;
}
if(c2 > numsSize / 3) {
*returnSize = *returnSize + 1;
flag |= 2;
}
res = (int*)malloc((*returnSize)*sizeof(int));
switch(flag) {
case 0: break;
case 1: res[0] = n1;break;
case 2: res[0] = n2;break;
case 3: res[0] = n1; res[1] = n2;break;
default: break;
}
return res;
}
程序里可以清楚的看到返回的情况。开空间需要用malloc函数: malloc()。