算法面试题

最近到某公司面试后,被问到2个关于算法的题目:

1.最大子段和(一个经典的动态规划算法求解题)

2.已知数据类型栈,请实现队列。

 

代码如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[] { -1, 3, -5, 1, 8, -7, 8, -5, 6, -5, -6 };
Console.WriteLine(
"最大子段和是:"+MaxSum(a));


Queue q
= new Queue();
for (int i = 0; i < 10; i++) q.Push(i);
for (int i = 0; i < 11; i++) Console.WriteLine(q.Pop());
for (int i = 0; i < 10; i++) q.Push(i);
for (int i = 0; i < 11; i++) Console.WriteLine(q.Pop());
}

/// <summary>
/// 最大子段和
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
static int MaxSum(int[] array)
{
int b=0;
int sum=0;
for (int i = 0; i < array.Length; i++)
{
if (b > 0) b += array[i];
else b = array[i];
if (sum < b) sum = b;
}
return sum;

}
}

/// <summary>
/// 自定义队列
/// </summary>
class Queue
{
Stack
<int> sa = new Stack<int>();
Stack
<int> sb = new Stack<int>();

/// <summary>
/// 将元素插入队列
/// </summary>
/// <param name="item"></param>
public void Push(int item)
{
sa.Push(item);
}

/// <summary>
/// 从队列删除并返回一个元素
/// </summary>
/// <returns></returns>
public int? Pop()
{
if (IsEmpty()) return null;

if (sb.Count == 0)
{
while (sa.Count > 0) sb.Push(sa.Pop());
return sb.Pop();
}
else return sb.Pop();
}

/// <summary>
/// 判断队列是否为空
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
if (sa.Count == 0 && sb.Count == 0) return true;
else return false;
}


}
}

 

posted @ 2010-11-10 23:02  lipan  阅读(1503)  评论(6编辑  收藏  举报