229. Majority Element II**
生活随笔
收集整理的這篇文章主要介紹了
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.
Hint:
Boyer-Moore Algorithm:設出一個candidate和一個count,candidate初值隨便設,相同則count增加,否則count減小。
public class Solution {public List<Integer> majorityElement(int[] nums) {List<Integer> result =new ArrayList<>();if (nums==null) return result;int cad1 =0, cad2 = 1, count1=0, count2 = 0;for(Integer n:nums){if(n==cad1) count1+=1;else if(n==cad2) count2+=1;else if(count1 ==0){cad1= n;count1=1;}else if(count2==0){cad2 = n;count2 =1 ;}else{count1-=1;count2-=1;}}count1=0;count2=0;for(Integer n:nums){if(n==cad1) count1++;else if(n==cad2) count2++;}if(count1>nums.length/3) result.add(cad1);if(count2>nums.length/3) result.add(cad2);return result;} }總結
以上是生活随笔為你收集整理的229. Majority Element II**的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: audition cc变声插件_Adob
- 下一篇: MLP Coursework Machi