169. 多数元素
难度简单1159收藏分享切换为英文接收动态反馈
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
进阶:
- 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
思路:不同元素相互抵消
class Solution {public int majorityElement(int[] nums) {int cnt = 0, res = -1;for (int x : nums) {if (cnt == 0)res = x;if (res == x)cnt++;elsecnt--;}return res;}}
229. 求众数 II
给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
示例 1:
输入:[3,2,3]
输出:[3]
示例 2:
输入:nums = [1]
输出:[1]
示例 3:
输入:[1,1,1,3,3,2,2,2]
输出:[1,2]
提示:
1 <= nums.length <= 5 * 10-10 <= nums[i] <= 10
进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。
思路:**每三个不同元素相互抵消class Solution {public List<Integer> majorityElement(int[] nums) {int v1 = 0, v2 = 0, num1 = 0, num2 = 0;for (int x : nums) {if (v1 > 0 && x == num1)v1++;else if (v2 > 0 && x == num2)v2++;else if (v1 == 0) {num1 = x;v1++;}else if (v2 == 0) {num2 = x;v2++;}else {v1--;v2--;}}int c1 = 0, c2 = 0;for (int x : nums) {if (v1 > 0 && x == num1)c1++;if (v2 > 0 && x == num2)c2++;}List<Integer> res = new ArrayList<>();if (c1 > nums.length / 3)res.add(num1);if (c2 > nums.length / 3)res.add(num2);return res;}}
