Title Link: majority-element
/** * Given An array of size n, find the majority element. The majority element is the element, which appears more than? N/2? Times. Assume that the array was 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 The time complexity is O (n), the spatial complexity is O (1)//Because the most of the element is half and above, it can be offset with other elements, and the last remaining non-offset elements are the desired//array is divided into three blocks: NUM[0...I] is a merged array of not yet offset. NUM[I+1...J-1] Spare area, num[j...num.length-1] is the array to wait for cancellation//cancellation rules: if num[i] = Num[j] then num[j] into the num[0...i+1] Array//if num[i]! = Num[j] Num[i] and then 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 Implementation]