Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[Leet code] 619. Biggest Single Number

์ธ” 2023. 9. 2. 22:16

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ Problems, https://leetcode.com/problemset/all/์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โœ” ๋ฌธ์ œ

https://leetcode.com/problems/biggest-single-number/

 

Biggest Single Number - LeetCode

Can you solve this real interview question? Biggest Single Number - Table: MyNumbers +-------------+------+ | Column Name | Type | +-------------+------+ | num | int | +-------------+------+ This table may contain duplicates (In other words, there is no pr

leetcode.com

Table : MyNumbers

single number is a number that appeared only once in the MyNumbers table.

Find the largest single number. If there is no single number, report null.

The result format is in the following example.


โœ” ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

๋‹จ์ผ๊ฐœ์ธ ์ˆซ์ž์ค‘ ๊ฐ€์žฅ ํฐ ์ˆซ์ž๋ฅผ ์ถœ๋ ฅํ•ด์•ผํ•˜๋Š”๋ฐ ๋งŒ์•ฝ ๋‹จ์ผ๊ฐœ์ธ ์ˆซ์ž๊ฐ€ ์—†๋‹ค๋ฉด null์„ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

 

โ‘  ์ˆซ์ž๋ณ„ ๊ฐœ์ˆ˜(cnt)๋ฅผ ๊ตฌํ•ด์„œ            > group by์ ˆ

โ‘ก ์ˆซ์ž๋ณ„ ๊ฐœ์ˆ˜๊ฐ€ 1์ธ ๊ฒƒ์„ ์ฐพ๊ณ         > having์ ˆ

โ‘ข < โ‘ก > num ์ค‘์— ์ตœ๋Œ€ num์„ ์ฐพ๋Š”๋‹ค.

 

SELECT MAX(num) AS num
 FROM (
        SELECT num, COUNT(*) AS cnt
         FROM MyNumbers
         GROUP BY 1
         HAVING COUNT(*) = 1
        ) T1
 ;

 

FROM์ ˆ์˜ ์„œ๋ธŒ์ฟผ๋ฆฌ์—์„œ HAVING์ ˆ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋ฉ”์ธ SELECT์ ˆ์—์„œ WHERE์ ˆ๋กœ ๋‹จ์ผ๊ฐœ์ˆ˜ ์กฐ๊ฑด์„ ์„ค์ •ํ•ด์ค˜๋„ ๊ฒฐ๊ณผ๊ฐ’์„ ๋™์ผํ•˜๊ฒŒ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๋‹ค.

SELECT MAX(num) AS num
 FROM (
        SELECT num, COUNT(*) AS cnt
         FROM MyNumbers
         GROUP BY 1
      ) T1
 WHERE cnt = 1
 ;