id num
1 1
2 1
3 1
4 2
5 3
6 4
7 4
8 4

# 2.思路和解法

id num lagid
1 1 null
2 1 0
3 1 0
4 2 1
5 3 1
6 4 1
7 4 0
8 4 0

id num lagid rid gid
1 1 null xxx
2 1 0 1 1
3 1 0 2 1
4 2 1 xxx
5 3 1 xxx
6 4 1 xxx
7 4 0 1 6
8 4 0 2 6
``````-- 完整sql
## 解法1
SELECT num
FROM
(SELECT id,
num,
lagid,
(id-row_number() over(PARTITION BY num, lagid
ORDER BY id)) AS gid
FROM
(SELECT id,
num,
num- lag(num) (OVER PARTITION BY 1
ORDER BY id) AS lagid) tmp1
WHERE lagid=0 ) tmp2
GROUP BY num,
gid
HAVING count(*) >= 2

## 解法2
select
num,
gid,
count(1) as c
from
(
select
id,
num,
id-row_number() over(PARTITION BY num ORDER BY id) as gid
from
(select * from logs order by num,id) a
) b
group by num,gid
``````

``````SELECT num,
gid
FROM
(SELECT num,
id-row_number() OVER (PARTITION BY num
ORDER BY id) gid
FROM logs)
GROUP BY num,
gid
HAVING count(1) >= 3

``````

# 3.3 分析和解法

1. 首先考虑一轮遍历怎么写，应该很简单把，思路就是一个大小为3的窗口

2. 用一个flag来标志每一轮是否有改过数据。那么代码如下：

``````public int[] get(int[] input) {
if (input == null || input.length <=2)
return input;
boolean flag = false;
do {
flag = false;
for (int i=1;i+1 < input.length;i++){
if (input[i] < input[i+1] && input[i] < input[i-1] ) {
input[i] +=1;
if (!flag)
flag = true;
}
if (input[i] > input[i+1] && input[i] > input[i-1] ) {
input[i] -=1;
if (!flag)
flag = true;
}
}
} while(flag)
return input;
}
``````

https://www.cnblogs.com/hulichao/p/14092948.html

Scroll to Top