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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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