规范格式

This commit is contained in:
YDZ
2020-08-07 15:50:06 +08:00
parent 854a339abc
commit 4e11f4028a
1438 changed files with 907 additions and 924 deletions

View File

@ -0,0 +1,43 @@
package leetcode
// 解法一 暴力解法 O(nk)
func maxSlidingWindow1(a []int, k int) []int {
res := make([]int, 0, k)
n := len(a)
if n == 0 {
return []int{}
}
for i := 0; i <= n-k; i++ {
max := a[i]
for j := 1; j < k; j++ {
if max < a[i+j] {
max = a[i+j]
}
}
res = append(res, max)
}
return res
}
// 解法二 双端队列 Deque
func maxSlidingWindow(nums []int, k int) []int {
if len(nums) == 0 || len(nums) < k {
return make([]int, 0)
}
window := make([]int, 0, k) // store the index of nums
result := make([]int, 0, len(nums)-k+1)
for i, v := range nums { // if the left-most index is out of window, remove it
if i >= k && window[0] <= i-k {
window = window[1:len(window)]
}
for len(window) > 0 && nums[window[len(window)-1]] < v { // maintain window
window = window[0 : len(window)-1]
}
window = append(window, i) // store the index of nums
if i >= k-1 {
result = append(result, nums[window[0]]) // the left-most is the index of max value in nums
}
}
return result
}

View File

@ -0,0 +1,43 @@
package leetcode
import (
"fmt"
"testing"
)
type question239 struct {
para239
ans239
}
// para 是参数
// one 代表第一个参数
type para239 struct {
one []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans239 struct {
one []int
}
func Test_Problem239(t *testing.T) {
qs := []question239{
question239{
para239{[]int{1, 3, -1, -3, 5, 3, 6, 7}, 3},
ans239{[]int{3, 3, 5, 5, 6, 7}},
},
}
fmt.Printf("------------------------Leetcode Problem 239------------------------\n")
for _, q := range qs {
_, p := q.ans239, q.para239
fmt.Printf("【input】:%v 【output】:%v\n", p, maxSlidingWindow(p.one, p.k))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,44 @@
# [239. Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)
## 题目
Given an array *nums*, there is a sliding window of size *k* which is moving from the very left of the array to the very right. You can only see the *k* numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
**Example:**
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
**Note:**
You may assume *k* is always valid, 1 ≤ k ≤ input array's size for non-empty array.
**Follow up:**
Could you solve it in linear time?
## 题目大意
给定一个数组 nums有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口 k 内的数字。滑动窗口每次只向右移动一位。返回滑动窗口最大值。
## 解题思路
- 给定一个数组和一个窗口为 K 的窗口,当窗口从数组的左边滑动到数组右边的时候,输出每次移动窗口以后,在窗口内的最大值。
- 这道题最暴力的方法就是 2 层循环,时间复杂度 O(n * K)。
- 另一种思路是用优先队列,每次窗口以后的时候都向优先队列里面新增一个节点,并删除一个节点。时间复杂度是 O(n * log n)
- 最优的解法是用双端队列,队列的一边永远都存的是窗口的最大值,队列的另外一个边存的是比最大值小的值。队列中最大值左边的所有值都出队。在保证了双端队列的一边即是最大值以后,时间复杂度是 O(n),空间复杂度是 O(K)