Java for LeetCode 229 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.

解题思路:

《编程之美》寻找发帖水王的原题,两次遍历,一次遍历查找可能出现次数超过nums.length/3的数字,(出现三次不同的数即抛弃),第二次验证即可。

JAVA实现如下:

public List<Integer> majorityElement(int[] nums) {
        		List<Integer> list = new ArrayList<Integer>();
		if (nums == null || nums.length == 0)
			return list;
		int left = nums[0], right=nums[0];
		int count1 = 1, count2 = 0;
		for (int i = 1; i < nums.length; i++) {
			if (nums[i] == left)
				count1++;
			else if(right==left){
				right=nums[i];
				count2=1;
			}
			else if(right==nums[i])
				count2++;
			else if(count1==0){
				left=nums[i];
				count1=1;
			}
			else if(count2==0){
				right=nums[i];
				count2=1;
			}
			else{
				count2--;
				count1--;
			}
		}
		count1=0;count2=0;
		for(int i=0;i<nums.length;i++){
			if(nums[i]==left)
				count1++;
			else if(nums[i]==right)
				count2++;
		}
		if(count1>nums.length/3)
			list.add(left);
		if(count2>nums.length/3)
			list.add(right);
		return list;
    }

 

你可能感兴趣的:(Java for LeetCode 229 Majority Element II)