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.
这道题如果没有时间复杂度要求的话,还是很好处理的。
先付上当时一遍ac的思路。
class Solution {
public int majorityElement(int[] nums) {
int len=nums.length;
if(len==1)return nums[0];
int mid=(int)(len)/2;
Arrays.sort(nums);
return nums[mid];
}
}
这个思路的时间复杂度应该是O(nlogn),主要耗时间的是排序的过程,根据给定的数据,sort的时间复杂度不定,我们尚且以最优的思想去考虑,sort使用的是快排,排序之后,主要元素出现次数超过n/2,所以,可以理解为,中位数位置对应的元素一定是出现次数最多的元素。所以这个思路是正确的。
如果加上时间复杂度要求,比如我们要求时间复杂度为O(n)这时候,需要想一个更好的方法啦。
附上要求吧。Given an O(n)-time algorithm that returns the majority element of an n-element array,or null if none exists.
我的一种思路就是空间换时间。用map,key对应元素,value对应元素出现的次数。
public static int GetMajor(int [] arr) throws Exception { if (arr==null||arr.length==0){ throw new Exception("数组出现错误"); } Map<Integer,Integer> result=new HashMap<>(); for (int i=0;i<arr.length;i++) { if(result.containsKey(arr[i])) { int temp=result.get(arr[i]); result.put(arr[i],temp+1); } result.put(arr[i],1); } for (Map.Entry<Integer,Integer>entry:result.entrySet()){ if (entry.getValue()>(arr.length/2)){ return entry.getKey(); } } return -1; }
看leetcode关于这方面的讨论的时候,看到一个时间复杂度O(n),空间复杂度O(1)的很好地方法。
public static int majorityElement(int[] num) { int major=num[0], count = 1; for(int i=1; i<num.length;i++){ if(count==0){ count++; major=num[i]; }else if(major==num[i]){ count++; }else count--; } return major; }
总有一些算法惊艳了生活,激励我好好刷题,好好学习。