leecode 169. Majority Element(C语言,快速排序,堆排序,各类排序算法复杂度比较)22

来源:互联网 发布:手机三维绘图软件 编辑:程序博客网 时间:2024/06/06 05:40

贴原题:

Given an array of size n, find the majority element. The majority
element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element
always exist in the array.

Credits: Special thanks to @ts for adding this problem and creating
all test cases.

解析:
  本题是要找出一个数组中个数超过一半的数。
  我的思路是排序之后,中间的那个数就是我们所要找的数。但是我用快速排序来做就已经时间超出了,于是百度查了查各类排序算法的复杂度问题,发现堆排序的复杂度比快速排序还要低。便想到了用堆排序来解决这个问题。
  或许我应该写篇博客专门总结一下各类排序算法。
  
这里写图片描述(图源:百度图片,侵删)

快速排序: 时间超出

int majorityElement(int* nums, int numsSize) {    my_qsort(nums, numsSize);//快速排序我写过很多次了,这里就不重复了,或者可以调用库函数    return *(nums+numsSize/2);}

堆排序

void HeapAdjust(int arr[], int root, int len)  //堆调整,构建大顶堆{    int lChild=2*root;    int rChild=lChild+1;    int largest=root;    if(lChild<len && arr[lChild]>arr[largest])//判断左节点和根节点大小,把较大的放到根节点    {        largest=lChild;    }    if(rChild<len && arr[rChild]>arr[largest])//判断右节点和根节点大小,把较大的放到根节点    {        largest=rChild;    }    if(largest!=root)    {        arr[largest]=arr[root]^arr[largest];//把根、左、右三者的最大值放到根节点        arr[root]=arr[root]^arr[largest];        arr[largest]=arr[root]^arr[largest];        HeapAdjust(arr, largest, len);//交换之后其下的叶子节点可能不保持最大顶堆状态,递归调整    }}void HeapSort(int arr[], int length)  //堆排序 {      int i;    for(i=length/2; i>=0; i--)//调整非叶子节点部分,构建大顶堆    {        HeapAdjust(arr, i, length);    }    for(i=length-1; i>0; i--)//进行完一次堆调整之后最大值在堆头,把堆头和堆尾交换,调整个数减一    {        arr[i] = arr[0]^arr[i];//交换堆头和堆尾        arr[0] = arr[0]^arr[i];        arr[i] = arr[0]^arr[i];        HeapAdjust(arr, 0, i);//堆调整      }}int majorityElement(int* nums, int numsSize) {    HeapSort(nums, numsSize);    return *(nums+numsSize/2);}
阅读全文
0 0