Click here to see the full article post
@zhouyanghhu I just tried your solution for the data below. it returns duplicated Nums. (1 1 1.). As the editorial solution suggested, 'distinct' is needed.
| Id | Num |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
SELECT s.last_num AS consecutivenums FROM (
SELECT id,IF(@last_num = t.num,@rn:=@rn+1,@rn:=1) col,
(@last_num :=t.num) last_num
FROM LOGS t,(SELECT @last_num :=0,@rn :=1) b) s WHERE s.col>=3;
That is 3 times.Not at least 3 times.So the answer doesn't perfect?
Slightly different approach to the outlined answer:
Another approach using a nested query. I think it is better
set @prev = null;
set @conCount = 0;
select distinct t.Num as ConsecutiveNums from
when @prev = Num then @conCount := @conCount + 1
when (@prev := Num) is not null then @conCount := 1
end as ConCount
) as t
where t.ConCount = 3
select a.num as ConsecutiveNums
select count(num) as count1, num
group by num
where a.count1 > 3
I got the correct result, but cant submit it ...who can tell me there is any problem with my code???thanks very much
@JoyJoe The description require the number that appears consecutively for at least three times，not just count it. So you have to solve the problem of consecutiveness.
@Zhenguo0 OK I know, thanks very much. I will try it again !!!
select Num from (select Num,count(Num) as qw from Logs group by Num) qwe where qw>=3
Why is this the wrong answer?
Do we need two seperate joins , will this work
l1.Id = l2.Id and l1.Id = l2.Id + 1 and l1.Id = l2.Id + 2, this will return three rows for one id that have three consecutive matches... then we can do group by count and having >= 3
select distinct W as ConsecutiveNums from (
select Num ,
@t:=case when @p1=Num and @p2=Num then Num else -999 end as W,
case when @t <> -999 then @p2:=-2999 else @p2:=@p1 end,
case when @t <> -999 then @p1:=-1999 else @p1:=Num end
from Logs ,(select @t:=0, @p1:=-1999,@p2:=-2999) a
where x.W <> -999
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.