【Leetcode】Majority Element II

题目链接:https://leetcode.com/problems/majority-element-ii/

题目:

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?

思路:
1、先排序,然后判断,时间复杂度为O(nlog n)
2、主元素个数要超过1/3,所以最多只有两个主元素,先找到数组中个数最多的两个元素,再遍历一遍看它们个数是否大于1/3.。时间复杂度为O(n)
算法1:
	public List<Integer> majorityElement(int[] nums) {
		List<Integer> list = new ArrayList<Integer>();
		Arrays.sort(nums);
		int times = nums.length / 3;
		int tmp = 1;
		for (int i = 0; i < nums.length; i++) {
			while (i + 1 < nums.length && nums[i + 1] == nums[i]) {
				i++;
				tmp++;
			}
			if (tmp > times) {
				list.add(nums[i]);
			}
			tmp = 1;
		}
		return list;
	}
算法2:
	public List<Integer> majorityElement(int[] nums) {
		List<Integer> list = new ArrayList<Integer>();
		int m1 = 0, m2 = 0, t1 = 0, t2 = 0; // m1,m2为次数最多的两个元素
		for (int i = 0; i < nums.length; i++) {//找到两个候选主元素
			if (t1 == 0) {
				m1 = nums[i];
				t1++;
			} else if (t2 == 0&&nums[i]!=m1) {//找到第二个候选主元素
				m2 = nums[i];
				t2++;
			} else {//已经有候选元素
				if (nums[i] != m1 && nums[i] != m2) {//当前元素非候选元素
					t1--;
					t2--;
				} else if (nums[i] == m1) {
					t1++;
				} else if (nums[i] == m2) {
					t2++;
				}
			}
		}
		t1=0;
		t2=0;
		for (int i = 0; i < nums.length; i++) {// 计算两元素的次数
			if (nums[i] == m1)
				t1++;
			if (nums[i] == m2)
				t2++;
		}
		if (t1 > nums.length / 3) // 如果大于1/3
			list.add(m1);
		if (m1 != m2) {// 防止数组中元素相同的情况
			if (t2 > nums.length / 3)
				list.add(m2);
		}
		return list;
	}



你可能感兴趣的:(【Leetcode】Majority Element II)