【题解】Leetcode 41. 缺失的第一个正数 / 84. 柱状图中最大的矩形

41. 缺失的第一个正数

给定一个未排序的整数数组,找出其中没有出现的最小的正整数。

你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。

// 将数字 num 放到 num-1 位置,只需要一个临时变量
// 然后扫描一次即可
func firstMissingPositive(nums []int) int {
	for _, num := range nums {
		for now:=num; now>0 && now<=len(nums) && now!=nums[now-1]; {
			now, nums[now-1] = nums[now-1], now 
		}
	}
	res := 1
	for ; res<=len(nums); res++ {
		if nums[res-1]!=res {
			break
		}
	}
    return res
}

84. 柱状图中最大的矩形

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。


单调栈经典题目,我实现的略复杂了些。

实际上,当某个位置出栈时,即碰到了右侧第一个比它小的位置。

当某个位置入栈后,它的左边就是左侧第一个比它小的位置。

在原数组两端加两个哨兵,甚至可以一次循环直接得出结果。

// 对于每个位置 i,我们求其左右两侧第一个小于 height[i] 的位置.
// 使用一个栈来维护单调递增的位置,当某个位置出栈时,即碰到了比它小的。
func largestRectangleArea(heights []int) int {
	n := len(heights)
    stack, top := make([]int, n), 0 // 初始化栈
    lef, rig := make([]int, n), make([]int, n) 

    for i:=0; i<n; i++ {
    	for top>0 && heights[stack[top-1]]>heights[i] {
    		rig[stack[top-1]] = i; top--
    	}
    	stack[top] = i; top++
    }
    for top>0 {
    	rig[stack[top-1]] = n; top--
    }

    for i:=n-1; i>=0; i-- {
    	for top>0 && heights[stack[top-1]]>heights[i] {
    		lef[stack[top-1]] = i; top--
    	}
    	stack[top] = i; top++
    }
    for top>0 {
    	lef[stack[top-1]] = -1; top--
    }
    
    ans := 0
    for i:=0; i<n; i++ {
    	if now:=heights[i]*(rig[i]-lef[i]-1); now>ans {
    		ans = now
    	}
    }
    return ans
}
发布了382 篇原创文章 · 获赞 317 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/m0_37809890/article/details/104365835