C#在不使用集合的情况下从堆栈中推送(int data)、pop()和getmin()值
我想检索在堆栈中输入的最小值(通过push(int)) 这是我迄今为止为C#在不使用集合的情况下从堆栈中推送(int data)、pop()和getmin()值,c#,C#,我想检索在堆栈中输入的最小值(通过push(int)) 这是我迄今为止为Push和Pop编写的示例代码,但我没有得到最小值 class Program { private int StackSize; public int StackSizeSet { get { return StackSize; } set { StackSize = value; } } public int top; Object[]
Push
和Pop
编写的示例代码,但我没有得到最小值
class Program
{
private int StackSize;
public int StackSizeSet
{
get { return StackSize; }
set { StackSize = value; }
}
public int top;
Object[] item;
public Program()
{
StackSizeSet = 10;
item = new Object[StackSizeSet];
top = -1;
}
public void isMinimum()
{
for (int i = 0; i <StackSizeSet; i++)
{
Console.WriteLine("Mianimum value is" + item[top]);
Console.ReadKey();
}
}
public bool isEmpty()
{
if (top == -1) return true;
return false;
}
public void Push(int value)
{
if (top == (StackSize - 1))
{
Console.WriteLine("Stack is full!");
}
else
{
item[++top] = value;
Console.WriteLine("Item pushed successfully!");
Console.WriteLine(item[top]);
}
}
public object Pop()
{
if (isEmpty())
{
Console.WriteLine("Stack is empty!");
Console.ReadLine();
return "No elements";
}
else
{
Console.WriteLine("Items popped successfully");
return item[top--];
}
}
static void Main(string[] args)
{
Program p = new Program();
p.Push(10);
p.Pop();
p.isMinimum();
//Console.WriteLine(p);
Console.ReadKey();
}
}
类程序
{
私有整数堆栈大小;
公共整数堆栈大小集
{
获取{return StackSize;}
设置{StackSize=value;}
}
公共int top;
对象[]项;
公共计划()
{
StackSizeSet=10;
item=新对象[StackSizeSet];
top=-1;
}
公共空间最小()
{
对于(int i=0;i所有Minimum
方法都会迭代堆栈中的项。您可以使用LINQ非常轻松地获取最小值,但如果您想在不使用集合的情况下执行此操作,则可以执行很长的一段时间-遍历堆栈并继续存储最小值;一旦遍历堆栈,您将获得ans威尔
假设您使用的是int[]
而不是Object[]
(因此我们不必处理强制转换):
int minValue=item[0];
对于(int i=1;i项[i])
{
最小值=项目[i];
}
}
基本上,上面的代码将最小值设置为数组中的第一个元素(堆栈中最早的元素)
然后它将循环通过其余元素,将当前元素与当前最小值进行比较-如果当前元素较低,则最小值将更新为当前值
循环完成后,您将拥有堆栈的最小值。除项目本身外,您还应存储子堆栈的最小值。因此您将拥有:
int[] items;
int[] minima; //initialize in constructor
在Push
上,您可以将最小值添加到堆栈中:
public void Push(int value)
{
if (top == (StackSize - 1))
{
Console.WriteLine("Stack is full!");
}
else
{
item[++top] = value;
if(top == 0)
minima[top] = value;
else
minima[top] = Math.Min(value, minima[top - 1]);
Console.WriteLine("Item pushed successfully!");
Console.WriteLine(item[top]);
}
}
为了计算最小值,您只需查看最小值堆栈上最顶层的元素,这将为您提供O(1)
时间复杂度,而不是O(n)
下面是一个示例(从下到上堆叠):
示例代码在哪里?Mahmood附上了示例代码为什么在处理int
时使用Object[]
呢?int[]
不是更合适吗?是的,可以改为int[]谢谢Tim。我用int[]代替Object[]不客气。愉快的编码!+1这实际上是一个比我拥有的更优雅的解决方案。
public void Push(int value)
{
if (top == (StackSize - 1))
{
Console.WriteLine("Stack is full!");
}
else
{
item[++top] = value;
if(top == 0)
minima[top] = value;
else
minima[top] = Math.Min(value, minima[top - 1]);
Console.WriteLine("Item pushed successfully!");
Console.WriteLine(item[top]);
}
}
items minima
-------------
1 1
7 2
5 2
2 2
3 3