169. Majority Element
阿新 • • 發佈:2021-12-16
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;
}
}