LintCode-Majority Number II

Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.

Find it.

Note

There is only one majority number in the array

Example

For [1, 2, 1, 2, 1, 3, 3] return 1

Challenge

O(n) time and O(1) space

Solution:

复制代码
 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers
 4      * @return: The majority number that occurs more than 1/3
 5      */
 6     public int majorityNumber(ArrayList<Integer> nums) {
 7         if (nums.size()==0) return -1;
 8         if (nums.size()<3) return nums.get(0);
 9         int len = nums.size();
10 
11         int n1 = nums.get(0), n2 = 0;
12         int count1 = 1, count2 = 0;
13 
14         for (int i=1;i<len;i++)
15             if (nums.get(i)==n1)
16                 count1++;
17             else if (nums.get(i)==n2)
18                 count2++;
19             else {
20                 if (count1==0) {
21                     n1 = nums.get(i);
22                     count1 = 1;
23                 } else if (count2==0){
24                     n2 = nums.get(i);
25                     count2 = 1;
26                 } else {
27                     count1--;
28                     count2--;
29                 }
30             }
31 
32         if (count1!=0 && count2!=0){
33             count1 = 0;
34             count2 = 0;
35             for (int i=0; i<len;i++)
36                 if (nums.get(i)==n1) count1++;
37                 else if (nums.get(i)==n2) count2++;
38             if (count1>len/3) return n1;
39             else return n2;
40         } else if (count1!=0) return n1;
41         else return n2;
42                 
43     }
44 }
复制代码

 

posted @   LiBlog  阅读(278)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示