-2
整数(スタック)型のN個の要素を持つリストがあり、最小値を取得する必要がありますが、ループを作成したりリストをソートすることはできませんLinq.min()。私はそれが挑戦であるので、これを使うことはできません。 実装するメソッドはO(1)でなければなりません。 誰でもこれを行う方法に関する提案はありますか?ここに私のコード:ループやソートリストを使用せずに最小の整数を得る方法C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleStack
{
class Program
{
static void Main(string[] args)
{
Stack<int> Stack = new Stack<int>();
int sair = 0;
string print = string.Empty;
while (sair == 0)
{
showOptions();
int ChooseUser = int.Parse(Console.ReadLine());
if (ChooseUser == 0)
{
sair = 1;
}
else if (ChooseUser == 1)
{
Console.Clear();
Console.WriteLine("Enter a number to insert into the stack\n");
Stack.Push(int.Parse(Console.ReadLine()));
Console.Clear();
ShowStack(Stack);
Console.WriteLine(print);
}
else if (ChooseUser == 2)
{
Console.Clear();
if (Stack.Count == 0)
{
Console.WriteLine("There is no number in the Stack to be removed!");
}
else
{
Stack.Pop();
ShowStack(Stack);
Console.WriteLine(print);
}
}
else if (ChooseUser == 3)
{
Console.Clear();
if (Stack.Count == 0)
{
Console.WriteLine("There are no numbers in Stack!");
}
else
{
int menorInteiro = Stack.Min(item => item); /* I cant make this */
Console.WriteLine("Whole lower stack: " + menorInteiro);
}
}
else if (ChooseUser == 4)
{
Console.Clear();
ShowStack(Stack);
Console.WriteLine(print);
}
}
}
static public void showOptions() /* Method for displaying the screen options for the user */
{
Console.WriteLine("\nChoose an Option:\n");
Console.WriteLine("Exit type 0");
Console.WriteLine("Insert into Stack type 1");
Console.WriteLine("Remove from Stack type 2");
Console.WriteLine("View the smallest item in Stack type 3");
Console.WriteLine("Show Stack type 4\n");
}
public static void ShowStack(Stack<int> Stack) /* Method for displaying stack items */
{
Console.Write("\n\t");
if (Stack.Count > 0)
{
foreach (Object obj in Stack)
Console.Write(obj + "\n\t");
Console.WriteLine();
}
else
Console.WriteLine("Stack Empty!");
}
}
}
ユーザーが入力したときに最も低い数字を記録できるのですか? –
スタックを使用しないでください。 SortedListを使用します。 – Amit
これは、codegolf.stackexchange.com – Kris