题目1:134. 加油站
核心推论: 如果一个区间rest数组(gas - cost)总和小于0,那么这个区间都不可以作为起点。
所以只要某个区间剩余总和小于0, 那就从下一站开始作为起点。
// @lc code=start
class Solution {
func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int {
var totalSum = 0
var curSum = 0
var start = 0
for i in 0..<gas.count {
let rest = gas[i] - cost[i]
totalSum += rest
curSum += rest
if curSum < 0 {
start = i + 1
curSum = 0
}
}
if totalSum < 0 { return -1 }
return start
}
}
// @lc code=end
题目2:135.分发糖果
从左捋一遍,再从右捋一遍
// @lc code=start
class Solution {
func candy(_ ratings: [Int]) -> Int {
// 从最小的糖果向上推算
// 从左到右, 从右到左 来回捋一遍
if ratings.count == 1 { return 1 }
var stats = Array(repeating: 1, count: ratings.count)
for i in 1..<ratings.count {
stats[i] = ratings[i] > ratings[i - 1] ? stats[i - 1] + 1 : 1
}
for i in (0...ratings.count - 2).reversed() {
if ratings[i] > ratings[i + 1] {
stats[i] = max(stats[i], stats[i + 1] + 1)
}
}
return stats.reduce(0) { $0 + $1 }
}
}
// @lc code=end
题目3:860.柠檬水找零
思路:找钱优先找大额的
// @lc code=start
class Solution {
func lemonadeChange(_ bills: [Int]) -> Bool {
var five = 0, ten = 0, twenty = 0
for i in bills {
if i == 5 {
five += 1
continue
}
if i == 10 {
if five <= 0 { return false }
ten += 1
five -= 1
}
if i == 20 {
if ten > 0, five > 0 {
ten -= 1
five -= 1
} else if five >= 3 {
five -= 3
} else {
return false
}
}
}
return true
}
}
// @lc code=end
题目4: 406.根据身高重建队列
讲解
leetcode
按照身高降序排序,如果身高相同则 人数升序排序。
然后通过 位置插入。
// @lc code=start
class Solution {
func reconstructQueue(_ people: [[Int]]) -> [[Int]] {
let people = people.sorted {
if $0[0] == $1[0] {
return $0[1] < $1[1]
}
return $0[0] > $1[0]
}
print("\(people)")
var queue = [[Int]]()
for item in people {
queue.insert(item, at: item[1])
}
return queue
}
}
// @lc code=end