169 Majority Element [leetcode Java Implementation]

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.