import java.util.*;
import java.util.Map.Entry;
//在数组中找到出现次数大于N/K的数
public class GetNKNum{
//获得大于一半的数
public static void PrintHalfNum(int[]arr)
{
if(arr==null)
{
return ;
}
int times=0; //记录次数
int cand=0; //候选的数
//选出候选的数
for(int i=0;i!=arr.length;i++)
{
if(times==0)
{
cand=arr[i];
times=1;
}else if(arr[i]==cand)
{
times++;
}else{
times--; //不相同则删除两个不相同的数
}
}
times=0;
//验证是否是大于一半的cand数
for(int i=0;i!=arr.length;i++)
{
if(arr[i]==cand)
{
times++;
}
}
if(times>arr.length/2)
{
System.out.println(cand);
}else{
System.out.println("没有大于一半的数!");
}
}
//*****************************************************************************
//(进阶问题)获得大于N/K的数
public static void PrintNKNum(int[]arr,int k)
{
if(arr==null||k<0||k>arr.length||k<2)
{
return;
}
HashMap<Integer,Integer>cands=new HashMap<Integer,Integer>();
for(int i=0;i!=arr.length;i++)
{
if(cands.containsKey(arr[i]))
{
cands.put(arr[i],cands.get(arr[i])+1);
}
else{
//每到达k-1个数则删除
if(cands.size()==k-1)
{
allCandsMinusOne(cands);
}else{
cands.put(arr[i],1);
}
}
}
HashMap<Integer,Integer>reals=getReals(arr,cands);
boolean hasPrint=false;
for(Entry<Integer,Integer>set:cands.entrySet())
{
Integer key=set.getKey();
if(reals.get(key)>arr.length/k)
{
hasPrint=true;
System.out.print(key+" ");
}
}
System.out.println(hasPrint?" ":"没有符合条件的数");
}
//所有的候选者减去1
public static void allCandsMinusOne(HashMap<Integer,Integer>map)
{
List<Integer>removeList=new LinkedList<Integer>();//删除键值形成的链表
for(Entry<Integer,Integer>set:map.entrySet())
{
Integer key=set.getKey();
Integer value=set.getValue();
if(value==1)
{
removeList.add(key);
}
map.put(key,value-1);
}
for(Integer removeKey:removeList)
{
map.remove(removeKey);
}
}
//获得真正的候选集
public static HashMap<Integer,Integer>getReals(int[]arr,HashMap<Integer,Integer>cands)
{
HashMap<Integer,Integer>reals=new HashMap<Integer,Integer>();
for(int i=0;i!=arr.length;i++)
{
int curNum=arr[i];
if(cands.containsKey(curNum))
{
if(reals.containsKey(curNum))
{
reals.put(curNum,reals.get(curNum)+1);
}else{
reals.put(curNum,1);
}
}
}
return reals;
}
public static void main(String[]args)
{
//System.out.println("Hello");
int[]arr={2,2,2,2,2,4,4,4};
PrintHalfNum(arr);
int k=4;
PrintNKNum(arr,k);
}
}
在数组中找到出现次数大于N/K的数
最新推荐文章于 2023-04-08 21:36:55 发布