[?]*Majority Element II

來源:互聯網
上載者:User

標籤:

題目:

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.

 

解題思路:

與Majority Elements不同是這裡需要維護兩個變數n1和n2,如果下一個數與這兩個數都不同的時候,count1和count2都減一,如果下一個數與n1或者n2相等的時候,對應的count++。最後的結果必定在n1或者n2中。

 

代碼:

 1 public class Solution { 2     public int majorityNumber(ArrayList<Integer> nums) { 3         int n1 = nums.get(0), count1 = 1; 4         int index = 1; 5         for (; index < nums.size() && nums.get(index) == n1; index++) { 6             count1++; 7         } 8         if (index == nums.size()) { 9             return n1;10         }11         int n2 = nums.get(index), count2 = 1;12         for (int i = index + 1; i < nums.size(); i++) {13             if (nums.get(i) == n1) {14                 count1++;15             } else if (nums.get(i) == n2) {16                 count2++;17             } else {18                 if (count1 == 0) {19                     n1 = nums.get(i);20                     count1 = 1;21                 } else if (count2 == 0) {22                     n2 = nums.get(i);23                     count2 = 1;24                 } else {25                     count1--;26                     count2--;27                 }28             }29         }30         if (count1 == 0) {31             return n2;32         } else if(count2 == 0) {33             return n1;34         } else {35             int count = 0;36             for (int n : nums) {37                 if (n == n1) {38                     count++;39                 }40             }41             if (count > nums.size()/3) {42                 return n1;43             }44             return n2;45         }46     }47 }

 

reference:https://codesolutiony.wordpress.com/2015/03/15/lintcode-majority-element-ii/

[?]*Majority Element II

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.