能不能给一个时间复杂度和空间复杂度都为O(n)的算法代码过程

【统考真题】已知一个整数序列A=(a0,a1,…an-1) 其中0<=ai<n(0<=i<n) 若存在ap1=ap2=…=apm=x 且m>n/2,则称x为A的主元素,例如A=(0,5,5,3,5,7,5,5)则5为主元素,又如A=(0,5,5,3,5,1,5,7)则A中没有主元素,假设A中的n个元素保存在一个一维数组中,请设计一个尽可能高效的算法,求出A的主元素。若存在主元素,返回这个元素,若不存在主元素,返回-1.

就是只能一重循环和一维数组

int main()
{
    int A[] = {0,5,5,3,5,7,5,5};
    int n = sizeof(A)/sizeof(int);
    int *p = (int*)malloc(sizeof(int)*n);
    memset(p,0,n);
    int i=0;
    for(i=0;i<n;i++)   //核心处理,统计各元素出现的次数
        p[A[i]]++;
    for(i=0;i<n;i++)
    {
          if(p[i] > n/2)
          {
              printf("A的主元素为:%d",p[i]);
              break;
          }
    }
    free(p);
    if(i==n)
        printf("A没有主元素");
    return 0;
}


 public static int findValue(int[] arrs){
        int num = 1;
        int last=-1;
        for (int i:arrs){
            if (i == last){
                num++;
                continue;
            }
            num--;
            if (num == 0){
                last = i;
                num = 1;
            }
        }
        if (num>1){
            return last;
        }
        return  -1;
    }

    public static void main(String[] args) {
        int[] arr ={0,5,5,3,5,7,5,5};
        System.out.println(findValue(arr));
         arr = new int[]{0,5,5,3,5,1,5,7};
        System.out.println(findValue(arr));
    }

因为是超过元素的一半,那么假设这个元素为A,数组长度len,那么 数组A的个数> len/2,那么定义一个变量 计算相同元素的个数
如果元素不相同 计数个数-1,最终 这个计数>1 ,表明存在这样一个数
例子:
0,5,5,3,5,7,5,5

0-> num=1,last=1 0和-1不相等
5-> num=1,last =5 5和1不相等
5-> num=2,last = 5
3-> num=1,last =5
5-> num=2,last=5
7-> num=1,last = 5 5和7不等
5-> num = 2
5-> num = 3

0,5,5,3,5,1,5,7
0-> num:1,last:-1 0不等-1
5-> num:1,last:0 5不等0
5-> num:2,last:5
3-> num:1,last:5 3不等5
5-> num:2,last:5
1-> num:1,last:5 1不等5
5-> num:2,last:5
7-> num:1,last:5 7不等5