Solution with user defined variables


  • 24
    K
    select DISTINCT num FROM
    (select num,
    	case 
    		when @record = num then @count:=@count+1
    		when @record <> @record:=num then @count:=1 end as n
        from 
    	    Logs ,(select @count:=0,@record:=(SELECT num from Logs limit 0,1)) r
    ) a
    where a.n>=3

  • 0
    S

    Can anyone explain it? I am confused about it.


  • 0
    J

    SELECT DISTINCT t2.Num FROM
    (SELECT Num, @consecutiveTimes := IF((@prev = (@prev := Num)), @consecutiveTimes + 1, 1) times FROM Logs, (SELECT @prev := -1) t1) t2 WHERE times > 2;


  • 1
    Z

    Great solution ! I find the third select can be changed by
    "select @count:=0, @record:=num from Logs limit 1"


  • 0
    R

    Nice solution!


  • 0
    M

    How to explain when @record <> @record:=num then @count:=1


  • 0
    C

    @mayunjie I suppose it means that when the @record value is different from the Num value(the previous one is not equal to the next one), the consectiveness has been broken. Then, the counter @count will be reset to the initial value: '1'。


  • 0
    B

    My only question with regard to this answer lies in the following line:
    WHEN @record <> @record:=Num THEN @count:=1

    I understand this is to check if the previous Num from last row equal to the Num from the current row. So is @record <> @record:=Num a assignment as well? It compares the original value in @record and the new value Num in the new @record?

    Is is comparison and assignment at the same time?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.