【LeetCode】169. Majority Element(Easy)解题报告
题目地址:https://leetcode.com/problems/majority-element/#/description
题目描述:
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.
Solution1:
//time : O(nlogn)
//space : O(1)
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
Solution2:
//time : O(n)
//space : O(n)
class Solution {
public int majorityElement(int[] nums) {
Map<Integer , Integer> map = new HashMap<>();
int res = 0;
for(int num : nums){
if(!map.containsKey(num)){
map.put(num,1);
}else{
map.put(num,map.get(num)+1);
}
if(map.get(num) > nums.length/2){
res = num;
break;
}
}
return res;
}
}
Solution3:
//time : O(n)
//space : O(1)
//每次找出一对不同的元素,从数组中删除,直到数组为空或者只有一种元素
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int res = 0;
for(int num : nums){
if(count == 0){
res = num;
}
if(num != res){
count--;
}else{
count++;
}
}
return res;
}
}
Date:2017年6月3日