水王问题java解法

本文介绍了一种名为“剩者为王”的算法实现,该算法通过不断删除数组中的元素来找出占据数组三分之一以上比例的数。代码示例使用了两个整数数组,并通过Find1方法实现了1/3水王的查找,最终打印出占据较大比例的候选数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

核心思想就是删除相应的比例,剩着为王,所占比例可以推广!


public class KingOfWater {
	public static void main(String[] args) {
		int a[]={3,3,3,5,3,3,2,3,2,3,3,3,0,9,0,8,4};
        int b[]={3,5,3,2,4,3,6,8,3,6,3,2,3,6,2,8,3,6,2,3,4,6,2,2,6};
        int candidate[] = new int[3];
       // Find(a,a.length);
        Find1(b,b.length,candidate);//1/3水王----可推广
        for (int i = 0; i < candidate.length; i++) {
			System.out.println(candidate[i]);
		}
	}
	
//	 static int Find(int []ID,int N)
//	{
//	        int candidate;
//	        int nTimes=0,i;
//	        for(i=0;i<N;i++)
//	        {
//	                if(candidate==ID[i])
//	                nTimes++;
//	                else if(nTimes==0)
//	                {
//	                        candidate=ID[i];
//	                        nTimes=1;
//	                }
//	                else
//	                        nTimes--;
//	        }
//	        return candidate;
//	}
	 static int[] Find1(int []ID,int N,int candidate[])
	{
	        int nTimes[] = new int[3],i;
	        nTimes[0]=0;
	        nTimes[1]=0;
	        nTimes[2]=0;
	        candidate[0]=0;
	        candidate[1]=0;
	        candidate[2]=0;
	        for(i=0;i<N;i++)
	        {
	                if(candidate[0]==ID[i])
	                        nTimes[0]++;
	                else if(candidate[1]==ID[i])
	                        nTimes[1]++;
	                else if(candidate[2]==ID[i])
	                        nTimes[2]++;
	                else if(nTimes[0]==0)
	                {
	                        candidate[0]=ID[i];
	                        nTimes[0]=1;
	                }
	                else if(nTimes[1]==0)
	                {
	                        candidate[1]=ID[i];
	                        nTimes[1]=1;
	                }
	                else if(nTimes[2]==0)
	                {
	                        candidate[2]=ID[i];
	                        nTimes[2]=1;
	                }
	                else
	                {
	                        nTimes[0]--;
	                        nTimes[1]--;
	                        nTimes[2]--;
	                }
	        }
	        
	        
	        
	        return candidate;
	}


	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值