Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3] Output: 3 Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
return nums[n/2];
}
}
T: O(n log n)
class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
n = n / 2;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > n) {
return entry.getKey();
}
}
return 0;
}
}
Time: O(n) Space: O(n)
class Solution {
public int majorityElement(int[] nums) {
int ele = 0, vote =0;
for(int num : nums){
if(num == ele && vote > 0){
vote +=1;
} else if(vote ==0){
ele = num;
vote = 1;
} else {
vote -=1;
}
}
return ele;
}
}
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;
}
}
Time: O(nlogn) Space: O(n)
for(int i=0; i<nums.length ; i++){
if(map.containsKey(nums[i])){
map.put(nums[i], map.get(nums[i]) + 1);
else{
map.put(nums[i], 1);
}
}
相同
for (int i = 0; i < n; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}