题目描述:
方法一(暴力法,最简单想到的):
不先把数组排个序,大概耗时2200多ms
排序之后大概耗时2100多ms。
代码:
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
for(int i = 0;i < nums.length;i++){
int count = 0;
for(int j = 0;j < nums.length;j++){
if(nums[i] == nums[j]){
count++;
}
}
if(count > nums.length / 2){
return nums[i];
}
}
return -1;
}
}
结果:
方法二(排序):
这句话说明了数组经过排序之后,数组下标n/2(向下取整时)一定是多数元素。
代码:
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
结果:
方法三(Map):
代码:
class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(Integer num : nums){
if(!map.containsKey(num)){
map.put(num,1);
}else{
map.put(num,map.get(num)+1);
}
}
Map.Entry<Integer,Integer> majorityEntry = null;
for(Map.Entry<Integer,Integer> entry : map.entrySet()){
if(majorityEntry == null || entry.getValue() > majorityEntry.getValue()){
majorityEntry = entry;
}
}
return majorityEntry.getKey();
}
}
结果: