您的位置:首页 > 职场人生

面试算法——6.Mingo Game

2015-12-08 09:57 489 查看
每行,每列,对角线,存在互异的一组数据,则称找到了一个Mingo;

input: 随机1到1,000,000的数填充100*100的数组

output:Mingo的个数,以及最先出现的位置。

package ch_1_stackandqueue;

import java.util.HashSet;
import java.util.Set;

/**
* @author xiongquan
*Timestamp:20151208
*/
public class Pro_1_MingoSet {

/*
* 使用集合来判断每行,每列以及对角线元素是否 互异
*
* 根据集合中元素个数,可以得到结果
*
* */
private static Set<Integer> set;
private static int iarr[][];
private int len;
private int count;

public Pro_1_MingoSet()
{
set = new HashSet<>();
}

public void deal()
{
len = iarr.length;
int x=-1;
int y=-1;
//set.clear();
//row
for(int i=0;i<len;i++)
{
set.clear();
int j;
for(j=0;j<len;j++)
{
set.add(iarr[i][j]);
}
if(set.size()==len)
{
if(x==-1 && y==-1)
{
x=i;
y=0;
}else if(i<=x)
{
x=i;
y=0;
}
count++;
}
}

//column
for(int i=0;i<len;i++)
{
set.clear();
int j;
for(j=0;j<len;j++)
{
set.add(iarr[j][i]);
}
if(set.size()==len)
{
if(x==-1)
{

x=0;
y=i;
}else
{
if(j<=x)
{
x=j;
y=i;
}
}
count++;
}
}

//+diagonal
int k;
set.clear();
for(k=0;k<len;k++)
{

set.add(iarr[k][k]);

}
if(set.size()==len)
{
if(x==-1)
{
x=k;
y=k;
}else
{
if(0<=x&&0<=y)
{
x=0;
y=0;
}
}
count++;
}

//-

set.clear();
for(k=0;k<len;k++)
{

set.add(iarr[k][len-1-k]);

}
if(set.size()==len)
{
if(x==-1)
{
x=0;
y=len-1;
}else
{
if(0<=x)
{
x=0;
y=0;
}
}
count++;
}

System.out.println("坐标:"+x+","+y+"\nmingo个数:"+count);
}

public static void main(String[] args)
{
Pro_1_MingoSet test = new Pro_1_MingoSet();

//input the test data
iarr = new int[][] {
{ 1, 2, 2 },
{ 1, 3, 3 },
{ 3, 1, 2 } };
//

test.deal();

System.out.println(Integer.MAX_VALUE);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: