Majority Element

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里的类方法确实能快很多。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值