169 Majority Element [LeetCode Java實現]

來源:互聯網
上載者:User

標籤:java   leetcode   演算法   

題目連結:majority-element


/** * Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times.You may assume that the array is non-empty and the majority element always exist in the array. * */public class MajorityElement {//40 / 40 test cases passed.//Status: Accepted//Runtime: 253 ms//Submitted: 1 minute ago//時間複雜度為 O(n), 空間複雜度為 O(1)//由於最多的那個元素佔一半及以上, 故可以和別的元素相互抵消,最後剩下的未抵消掉的元素為所求//將數組分成三塊:num[0...i]為 歸併的 還未抵消的數組, num[i+1...j-1]空閑區, num[j...num.length-1]為等待抵消的數組//抵消規則:若num[i] = num[j] 則把num[j]歸入num[0...i+1]數組中// 若num[i] != num[j] 則把num[i] 抵消掉 然後 i--    static int majorityElement(int[] num) {            int i = -1;            for (int j = 0; j < num.length; j++) {            if(i == -1) num[++i] = num[j];        else {            if(num[j] == num[i]) num[ ++i] = num[j];     else i --;}    }    return num[0];    }public static void main(String[] args) {System.out.println(majorityElement(new int[]{4}));System.out.println(majorityElement(new int[]{4, 4, 5}));System.out.println(majorityElement(new int[]{4, 3, 3}));System.out.println(majorityElement(new int[]{4, 3, 4}));}}


169Majority Element [LeetCode Java實現]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.