229. Majority Element II

来源:互联网 发布:退役特种兵知乎 编辑:程序博客网 时间:2024/06/06 05:42

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?
  2. Do you have a better hint? Suggest it!

先排序,遍历一次,记录每个数值出现的次数如果出现次数超过1/3长度把这个值加入list 否则 置1重新开始

注意集中corner  长度 为1 、2   nums[0]是否等于nums[1]   不要重复加到list里,

再遍历之后如果后1/3是一个符合要求的数需要检查一下 遍历之后的tem_len是否大于1/3的长度  是more than  >不是>=

!!!!!限制了时间复杂度所以不能排序 尴尬

public class Solution {    public List<Integer> majorityElement(int[] nums) {        List<Integer> list=new ArrayList<Integer>();        if(nums.length==0||nums==null) return list;        Arrays.sort(nums);        int len=nums.length;        int tem_len=1;        if(nums.length==1||(nums.length==2&&nums[0]==nums[1])){           list.add(nums[0]);           return list;        }        else if(nums.length==2){            list.add(nums[0]);            list.add(nums[1]);            return list;        }        for(int i=0;i<len-1;i++){            if(nums[i]==nums[i+1]){                tem_len++;            }            else {                if(tem_len>len/3){                    // tem_len=1;                    list.add(nums[i]);                                    }                tem_len=1;            }        }        if(tem_len>len/3) list.add(nums[len-1]);        return list;    }}

用摩尔投票法:

http://www.bubuko.com/infodetail-977326.html

先遍历一遍数组,找出出现次数最多的两个数,再遍历一遍数组记录这两个数值出现的次数是否超过1/3次

 public List<Integer> majorityElement(int[] nums) {                List<Integer> list=new ArrayList<Integer>();        if(nums==null||nums.length==0) return list;        int len=nums.length;        int a=0;        int b=0;        int cnt1=0;        int cnt2=0;        for(int n:nums){            if(n==a){                cnt1++;                a=n;            }            else if(n==b){                cnt2++;                b=n;            }            else if(cnt1==0){                cnt1++;                a=n;            }            else if(cnt2==0){                cnt2++;                b=n;            }            else {                cnt1--;                cnt2--;            }        }         cnt1=cnt2=0;        for(int n:nums){            if(n==a) cnt1++;            if(n==b) cnt2++;        }        if(cnt1>len/3) list.add(a);        if(a==b) return list;        if(cnt2>len/3) list.add(b);        return list;    }

见超哥分析

discuss中的方法将出cnt1==0与a==n    cnt2==0与b==n 进行或,出现问题{1,2,2,3,2,1,1,3} 在进行到索引值为4也就是nums[4]=2时 cnt1==0 a=2 但此时b=2同时计了这一个数出现问题,应该先判断a和b中有没有当前遍历的值n



0 0
原创粉丝点击