[Java] Majority Element II 找众数2

来源:互联网 发布:萧亚轩事业 知乎 编辑:程序博客网 时间:2024/06/05 16:39

leetcode 链接 :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.

简要翻译:

就是给定一个含有n个数的数组,找到所有出现次数大于⌊ n/3 ⌋次的数。算法要求线性时间复杂度O(N),空间复杂度O(1).

此题如果采用先排序在去查找的话,显然是不能满足时间复杂度的,因为基于比较的排序最快也要O(N*logN)

根据我的上一篇博客(http://blog.csdn.net/lyy_hit/article/details/47616641)的解题思路,我们是可以在O(N)的时间复杂度解决问题的。

首先我们要分析,到底有几个数是满足条件的。很显然可能的情况就是0或1或2个数,为什么大于3就不行呢? 根据反正法是可以证明的,此处省略

在实现的过程中呢,我们可以假设存在两个数是满足条件的,用两个临时变量来存储,找到这两个数之后,因为可以证明若存在,必定就是临时变量存储的这两个数。因此我们可以再次遍历一次数组来统计出现的次数,若满足条件则是所要找的数,若不满足则不是。

代码实现如下:

package com.easy;import java.util.ArrayList;import java.util.List;public class MajorityElementII{public static void main(String[] args){// TODO Auto-generated method stubint []nums = {2, 2};//{-1, 1, 1, 1, 2, 1};//{1, 3, 1, 2, 3, 4, 2, 2, 3, 3, 2};List<Integer> list = majorityElement(nums);for (int i = 0; i < list.size(); i++){System.out.println(list.get(i));}}public static List<Integer> majorityElement(int[] nums) {        List<Integer> list = new ArrayList<Integer>();        int A = 0, B = 0;        int cntA = 0, cntB = 0;        for (int i = 0; i < nums.length; i++)        {        if (cntA == 0 && cntB == 0)        {        A = nums[i]; cntA++;        }else if (cntA > 0 && cntB == 0)        {        if (A != nums[i])        {        B = nums[i]; cntB++;        }else        {        cntA++;        }        }else if (cntA == 0 && cntB > 0)        {        if (B != nums[i])        {        A = nums[i]; cntA++;        }else        {        cntB++;        }        }else        {        if (A == nums[i])        {        cntA++;        }else if (B == nums[i])        {        cntB++;        }else        {        cntA--; cntB--;        }        }        //        System.out.println("A = "+A+" cntA = " + cntA + " B = " + B + " cntB = " + cntB);        }        if (cntA > 0)        {        cntA = 0;        for (int i = 0; i < nums.length; i++)        {        if (A == nums[i])        {        cntA++;        }        }        if (cntA > nums.length/3)        {        list.add(A);        }        }        if (cntB > 0)        {        cntB = 0;        for (int i = 0; i < nums.length; i++)        {        if (B == nums[i])        {        cntB++;        }        }        if (cntB > nums.length/3)        {        list.add(B);        }        }        return list;    }}

ps:在实现过程中要注意分情况,不能漏掉任何一种情况

0 0
原创粉丝点击