题目描述:
    image.png
    解析:摩尔投票法

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. //摩尔投票法
    4. int majorValue=0;
    5. int count=0;
    6. for(int num:nums){
    7. if(count==0){
    8. majorValue=num;
    9. count+=1;
    10. }else if(num==majorValue){
    11. count+=1;
    12. }else{
    13. count-=1;
    14. }
    15. }
    16. return majorValue;
    17. }
    18. }

    变题:如果是要找出出现次数大于【n/3】的元素
    同样使用摩尔投票法,改进版

    1. class Solution {
    2. public List<Integer> majorityElement(int[] nums) {
    3. //摩尔投票法的改进版
    4. int value1=0,value2=0,count1=0,count2=0;
    5. ArrayList<Integer> res = new ArrayList<>();
    6. for (int num : nums) {
    7. if(value1==num){
    8. count1+=1;
    9. }else if(value2==num){
    10. count2+=1;
    11. }else if (count1==0){
    12. value1=num;
    13. count1+=1;
    14. }else if(count2==0){
    15. value2=num;
    16. count2+=1;
    17. }else {
    18. count1-=1;
    19. count2-=1;
    20. }
    21. }
    22. if (count1>0){
    23. count1=0;
    24. for (int num : nums) {
    25. if(num==value1) count1+=1;
    26. }
    27. if (count1>nums.length/3) res.add(value1);
    28. }
    29. if (count2>0){
    30. count2=0;
    31. for (int num : nums) {
    32. if(num==value2) count2+=1;
    33. }
    34. if (count2>nums.length/3) res.add(value2);
    35. }
    36. return res;
    37. }
    38. }