c# Leetcode 496 下一个更大元素 I (栈)

思路很清晰:

倒叙入栈,然后拿要对比的依次进行比较,找到后面第一个大于的即可。

public class Solution {
    public int[] NextGreaterElement(int[] findNums, int[] nums) {
        int[] res = new int[findNums.Length];
			var stack = new Stack<int>();
			
			for (int i = nums.Length-1; i>=0; i--)
			{
				stack.Push(nums[i]);
			}
			for (int i = 0; i < findNums.Length; i++)
			{
				res[i] = GetRes(findNums[i], nums);
			}
			return res;
    }
    private static int GetRes(int item, int[] nums)
		{
			Stack<int> temp = new Stack<int>();
			for (int i = nums.Length - 1; i >= 0; i--) 
					temp.Push(nums[i]);
			while (true)
			{
				if (temp.Peek()==item)
				{
					while (true)
					{
						if (temp.Peek()>item)
						{
							return temp.Peek();
						}
						else
						{
							temp.Pop();
						}
						if (temp.Count == 0) break;
					}
				}
				else
				{
					temp.Pop();
				}
				if (temp.Count == 0) break; 
			}
			return -1;
		}
}

调用一下:

		public static void Main(string[] args)
		{
			int[] n1 = new int[] { 4,1,2 },n2=new int[] {2,4,3,1 };
			int[] st= NextGreaterElement(n1,n2);
			Console.Write(st); 
			Console.ReadKey();
		}

执行用时: 524 ms, 在Next Greater Element I的C#提交中击败了10.64% 的用户

虽然解决了问题,创建栈的次数却为  nums.length 次

猜你喜欢

转载自blog.csdn.net/us2019/article/details/86599931
今日推荐