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.
public class Solution {
public int majorityElement(int[] num) {
Sort(num, 0, num.length - 1);
return num[num.length / 2];
}
public int getMiddle(int a[], int low, int high) {
int mid = a[low];
while (low < high) {
while (low < high && a[high] > mid)
-- high;
a[low ++] = a[high];
while (low < high && a[low] < mid)
++ low;
a[high --] = a[low];
}
a[low] = mid;
return low;
}
目的第一反应就是先排序,然后直接return 中间项,所以先将数组按照复杂度最低的快排进行排序,然后输出,但是运行报错了,如下:
我理解的意思是排序过程复杂度太高了,后来看到有人写了下面的代码:
public class Solution {
public int majorityElement(int[] num) {
Arrays.sort(num);
return num[num.length/2];
}
}
直接用到了Java里的Arrays类的sort()方法,这样写就可以accepted。很好奇sort()的复杂度,所以特意去查了一下:
数组元素<7个的时候 用的是冒泡排序;
数组元素>7个的时候 用的是快速排序;所以说sort()最优的时间复杂度应该等于快排的O(nlogn)才对呀,可是为什么直接写一个快排函数会报错呢?郁闷。。。不过不得不承认,直接调用Java里的类方法确实能快很多。