接雨水
动态规划:找到当前位置,min(max左边,max右边),与当前位置计算差值可以得到当前位置接的雨水。
class Solution {
public int trap(int[] height) {
if (height == null || height.length == 0) return 0;
int lastIdx = height.length - 2;
int[] rightMaxes = new int[height.length];
for (int i = lastIdx; i >= 1; i--) {
rightMaxes[i] = Math.max(rightMaxes[i + 1], height[i + 1]);
}
// 遍历每一根柱子,看看每一根柱子上能放多少水
int water = 0, leftMax = 0;
for (int i = 1; i <= lastIdx; i++) {
leftMax = Math.max(leftMax, height[i - 1]);
// 求出左边最大、右边最大中的较小者
int min = Math.min(leftMax, rightMaxes[i]);
// 说明这根柱子不能放水
if (min <= height[i]) continue;
// 说明这根柱子能放水
water += min - height[i];
}
return water;
}
}
优化: 可以通过求得当前遍历到元素第二小的数值
func trap(_ height: [Int]) -> Int {
if height.isEmpty {
return 0
}
var l = 0, r = height.count - 1, water = 0, lowMax = 0
while (l < r) {
var lower: Int
if (height[l] <= height[r]) {
lower = height[l]
l += 1
} else {
lower = height[r]
r -= 1
}
// 抛去当前元素后,第二大的数值
lowMax = max(lowMax, lower)
water += lowMax - lower
}
return water
}
盛水最多的容器
思路
双指针,height比较小的元素向中间靠拢
func maxArea(_ height: [Int]) -> Int {
if height.isEmpty {
return 0
}
var l = 0, r = height.count - 1, water = 0
while l < r {
if height[l] <= height[r] {
let minH = height[l]
water = max(water, (r - l) * minH)
while (l < r && height[l] <= minH) {
l += 1
}
} else {
let minH = height[r]
water = max(water, (r - l) * minH)
while(l < r && height[r] <= minH) {
r -= 1
}
}
}
return water
}
会议室II
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let arrays = [[0, 30], [5, 10], [15, 20]]
print(minMeetingRooms(intervals: arrays))
let arrays1 = [[7, 10], [2, 4]]
print(minMeetingRooms(intervals: arrays1))
}
func minMeetingRooms(intervals: [[Int]]) -> Int {
if intervals.isEmpty {
return 0
}
var begins: [Int] = []
var ends: [Int] = []
for i in 0 ..< intervals.count {
begins.append(intervals[i][0])
ends.append(intervals[i][1])
}
begins.sort(by: <)
ends.sort(by: <)
var room = 0, endIndex = 0
for begin in begins {
if begin >= ends[endIndex] {
endIndex += 1
} else {
room += 1
}
}
return room
}
}
合并两个有序数组
func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var i1 = m - 1, i2 = n - 1, cur = m + n - 1
while i2 >= 0 {
if i1 >= 0 && nums2[i2] < nums1[i1] {
nums1[cur] = nums1[i1]
cur -= 1
i1 -= 1
} else {
nums1[cur] = nums2[i2]
cur -= 1
i2 -= 1
}
}
}
Z 字形变换
思路
:关键点在于理解,将加入方向调转
func convert(_ s: String, _ numRows: Int) -> String {
if numRows == 1 {
return s
}
var arrays = [String](repeating: "", count:numRows)
var currentRow = 0
var goingDown = false
for character in s {
arrays[currentRow].append(character)
if currentRow == numRows - 1 || currentRow == 0 {
goingDown = !goingDown
}
// 关键点就是这里的翻转,从上到下后改为从下到上
currentRow += goingDown ? 1 : -1
}
return arrays.joined()
}