169. Majority Element
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
Constraints:
n == nums.length
1 <= n <= 5 * 104
-231 <= nums[i] <= 231 - 1
Follow-up: Could you solve the problem in linear time and in O(1) space?
解题思路:关键在于多数元素>n/2, 多数元素唯一;
- 先排序,因为
关键,故(n)/2 肯定为指定的数
class Solution {
public int majorityElement(int[] nums) {
java.util.Arrays.sort(nums);
return nums[(nums.length)/2];
}
}
- 建立hashmap。存储出现的所有的数的个数,当该数的个数>n/2时,直接return
class Solution {
public static int majorityElement(int[] nums) {
HashMap<Integer, Integer> number = new HashMap<Integer, Integer>();
for(int num:nums){
if(null == number.get(num)){
number.put(num, 1);
}else{
number.put(num, number.get(num)+1);
}
if(number.get(num)> nums.length/2){
return num;
}
}
return -1;
}
}
- 摩尔投票法。已知多数元素>n/2,那么比其他所有的元素累计还要多。利用摩尔投票类似“抵消”,或者多方打仗,如果自己人碰上自己人,加一,无伤亡;如果碰到其他人,两个人都伤亡。最后剩下来的肯定是拥有士兵最多的队伍。
class Solution {
public int majorityElement(int[] nums) {
int vote=0;
int result=0;
for(int num:nums){
if(vote==0){
result = num;
}
vote += num==result ? 1: -1;
}
return result;
}
}

浙公网安备 33010602011771号