標籤: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實現]