Problem: 169. 多数元素
题目描述
思路
1.哈希表
将数组中的每个元素作为键,其出现的次数作为值存入哈希表中,最终找出多数元素
2.排序
将数组进行升序排序,由于多数元素大于数组长度的一半,则排序后的数组中的中间位置一定是多数元素
复杂度
思路1:
时间复杂度:
O ( n ) O(n) O(n);其中 n n n是数组nums的大小
空间复杂度:
O ( n ) O(n) O(n)
思路2:
时间复杂度:
O ( n l o g n ) O(nlogn) O(nlogn)
空间复杂度:
O ( 1 ) O(1) O(1)
Code
思路1:
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (!map.containsKey(nums[i])) {
map.put(nums[i], 1);
} else {
map.put(nums[i], map.get(nums[i]) + 1);
}
}
for (Integer key : map.keySet()) {
if (map.get(key) > (nums.length / 2)) {
return key;
}
}
return -1;
}
}
思路2:
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}