[Leetcode 229] Majority element II

Source: Internet
Author: User

Given an integer array of size n, find all elements this appear more than times ? n/3 ? . The algorithm should run in linear time and in O (1) space.


Solution:

At most have both elements in the result, can and counter to record occurrence. Then calculate if match the condition.

Public list<integer> majorityelement (int[] nums) {list<integer> result = new arraylist<> ();        if (nums.length==0) return result;        int n1 = Nums[0];        int n2 = 0;        int count1 = 1;        int count2 = 0;            for (int i=1;i<nums.length;i++) {if (nums[i] = = n1) {count1++;            }else if (nums[i] = = n2) {count2++;                    }else{if (count1 = = 0) {n1 = nums[i];                count1++;                    }else if (Count2 = = 0) {n2 = Nums[i];                count2++;                }else{count1--;            count2--;        }}} count1 = 0;        Count2 = 0;            for (int i=0;i<nums.length;i++) {if (nums[i] = = n1) count1++;        if (nums[i] = = n2) count2++;        } if (COUNT1&GT;NUMS.LENGTH/3) Result.add (N1);        if (n1 = = n2) return result; if (count2>nUMS.LENGTH/3) Result.add (N2);    return result; }



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Leetcode 229] Majority element II

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.