今天有个以前的朋友去面试,里面有个2个算法题.他不会,让我帮忙看看,一看我自己都傻了.
1题:
1-1000放在含有1001个元素的数组中,只有唯一的一个元素值重复,其它均只出现
一次。每个数组元素只能访问一次,设计一个算法,将它找出来;不用辅助存储空
间,能否设计一个算法实现?
这个我倒是会,但不知大算法是否够好,求更好的算法
今天有个以前的朋友去面试,里面有个2个算法题.他不会,让我帮忙看看,一看我自己都傻了.
1题:
1-1000放在含有1001个元素的数组中,只有唯一的一个元素值重复,其它均只出现
一次。每个数组元素只能访问一次,设计一个算法,将它找出来;不用辅助存储空
间,能否设计一个算法实现?
这个我倒是会,但不知大算法是否够好,求更好的算法
Code
1static void Main(string[] args)
2 {
3 int[] list = new int[1001];
4
5 for (int i = 1; i < 1001; i++)
6 {
7 list[i - 1] = i;
8 }
9
10 Random random = new Random();
11
12 list[1000] = random.Next(1, 1000);
13
14 int sum1 = 0;
15
16 int sum2 = 0;
17
18 foreach (int i in list)
19 {
20
21 sum1 = sum1 + i;
22 }
23 for (int i = 1; i < 1001; i++)
24 {
25
26 sum2 = sum2 + i;
27 }
28
29
30 Console.WriteLine("重复的数字是:"+(sum1 - sum2).ToString());
31 Console.Read();
32 }
2: 四个女人过桥,夜间有一火把,每次最多过两个,必需带火把,
过桥速度不一样
no.1 1min
no.2 2min
no3 5min
no.4 10min
两个人过用最慢一个的速度,火把不能扔
如何在17min内四个女人都过桥
问题难点: 如果从需求中抽象出对象,并用程序输入
我写了很长代码怎么都得不到17, 求高人指点
个人代码
public class CrossBridge
{
public int CrossTime
{ get; set; }
public bool HasFire
{ get; set; }
public string WomanID { get; set; }
}
算法:
算法
static int Sum;
static void Main(string[] args)
{
int total = 100;
while (total > 17)
{
Sum = 0;
total = GotIt(NewList());
}
Console.Read();
}
static ArrayList NewList()
{
CrossBridge woman1 = new CrossBridge();
woman1.CrossTime = 1;
woman1.WomanID = "1";
CrossBridge woman2 = new CrossBridge();
woman2.CrossTime = 2;
woman2.WomanID = "2";
CrossBridge woman3 = new CrossBridge();
woman3.CrossTime = 5;
woman3.WomanID = "3";
CrossBridge woman4 = new CrossBridge();
woman4.CrossTime = 10;
woman4.WomanID = "4";
ArrayList womanLists = new System.Collections.ArrayList();
womanLists.Add(woman1);
womanLists.Add(woman2);
womanLists.Add(woman3);
womanLists.Add(woman4);
return womanLists;
}
static int GotIt(ArrayList lists)
{
Random r1 = new Random();
int i=r1.Next(0, lists.Count-1);
CrossBridge w1 = (CrossBridge)lists[i];
lists.Remove(w1);
int j=r1.Next(0,lists.Count-1);
CrossBridge w2 = (CrossBridge)lists[j];
lists.Remove(w2);
CrossBridge temp ;
Console.WriteLine("走过去的是: 第" + w1.WomanID.ToString() + "女人and " + "第" + w2.WomanID.ToString() + "个女人");
if (w1.CrossTime < w2.CrossTime)
{
temp = w1;
}
else
{
temp = w2;
}
Sum = Sum + w2.CrossTime + w1.CrossTime;
lists.Add(temp);
if (lists.Count != 1)
{
Console.WriteLine(temp.WomanID + "走回去了");
Console.WriteLine("现在的时间是:" + Sum.ToString());
GotIt(lists);
}
else
{
Sum = Sum - temp.CrossTime;
Console.WriteLine("总时间是:" + Sum.ToString());
System.Threading.Thread.Sleep(2000);
}
return Sum;
}