183. Customers Who Never Order

 

 문제 설명

 

Create table If Not Exists Customers (id int, name varchar(255))
Create table If Not Exists Orders (id int, customerId int)
Truncate table Customers
insert into Customers (id, name) values ('1', 'Joe')
insert into Customers (id, name) values ('2', 'Henry')
insert into Customers (id, name) values ('3', 'Sam')
insert into Customers (id, name) values ('4', 'Max')
Truncate table Orders
insert into Orders (id, customerId) values ('1', '3')
insert into Orders (id, customerId) values ('2', '1')

 

Table: Customers

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| customerId  | int  |
+-------------+------+
id is the primary key column for this table.
customerId is a foreign key of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.

 

id는 이 테이블의 프라이머리 키열입니다.
customerId는 [Customers]테이블에 있는 ID의 외부 키입니다.
이 표의 각 행은 주문의 ID와 주문 고객의 ID를 나타냅니다.

 

Write an SQL query to report all customers who never order anything.

Return the result table in any order.

The query result format is in the following example.

SQL 쿼리를 작성하여 아무것도 주문하지 않은 모든 고객을 보고합니다.
임의의 순서로 결과 테이블을 반환합니다.
쿼리 결과 형식은 다음과 같습니다.

 

 입출력 예

 

Example 1:

Input: 
Customers table:
+----+-------+
| id | name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+
Output: 
+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

 

 Oracle Query

 

select name as customers
from customers
where id not in
(select customerid from orders);

서브쿼리 (select customerid from orders)에서 customerid 결과가 아닌 id일 때, 컬럼 name 출력

* 참고 링크 : https://leetcode.com/problems/customers-who-never-order/discuss/1080196/Oracle-easiest-solution

https://stand-atop.tistory.com/144

 출처

 

https://leetcode.com/problems/customers-who-never-order/

627. Swap Salary

 

 문제 설명

 

Table: Salary

+----------------+-------------+
| Column Name | Type          |
+----------------+-------------+
| id                 | int             |
| name            | varchar       |
| sex               | ENUM        |
| salary            | int             |
+----------------+-------------+

id is the primary key for this table.
The sex column is ENUM value of type ('m', 'f').
The table contains information about an employee.

id는 이 테이블의 프라이머리 키입니다.
Sex 열은 유형의 ENUM 값('m', 'f')입니다.
표에는 직원에 대한 정보가 포함되어 있습니다.

 

Write an SQL query to swap all 'f' and 'm' values (i.e., change all 'f' values to 'm' and vice versa) with a single update statement and no intermediate temporary tables.

Note that you must write a single update statement, do not write any select statement for this problem.

The query result format is in the following example.

SQL 쿼리를 작성하여 모든 'f' 및 'm' 값을 단일 업데이트 문으로 스왑하고 중간 임시 테이블을 사용하지 않습니다(즉, 모든 'f' 값을 'm'으로 변경).

이 문제에 대한 select 문을 작성하지 말고 단일 업데이트 문을 작성해야 합니다.

쿼리 결과 형식은 다음과 같습니다.

 

 입출력 예

 

Example 1:

Input: 
Salary table:
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |
+----+------+-----+--------+
Output: 
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |
+----+------+-----+--------+
Explanation: 
(1, A) and (3, C) were changed from 'm' to 'f'.
(2, B) and (4, D) were changed from 'f' to 'm'.
 

 

 

 Oracle Query

 

UPDATE salary s
SET sex = 
CASE 
  WHEN sex='m' THEN 'f'
  WHEN sex='f' THEN 'm'
END;
update salary 
set sex = decode(sex,'m','f','m');

 

DECODE문 - ORACLE에서만 존재하는 함수

DECODE(컬럼명, 조건, True 결과값, False 결과값)

https://sseoui.tistory.com/110

* 참고 링크 : https://leetcode.com/problems/swap-salary/discuss/504204/Oracle-solution

https://leetcode.com/problems/swap-salary/discuss/708246/Using-Decode

 

 출처

 

https://leetcode.com/problems/swap-salary/

Not Boring Movies

 

 문제 설명

 

Create table If Not Exists cinema (id int, movie varchar(255), description varchar(255), rating float(2, 1))
Truncate table cinema
insert into cinema (id, movie, description, rating) values ('1', 'War', 'great 3D', '8.9')
insert into cinema (id, movie, description, rating) values ('2', 'Science', 'fiction', '8.5')
insert into cinema (id, movie, description, rating) values ('3', 'irish', 'boring', '6.2')
insert into cinema (id, movie, description, rating) values ('4', 'Ice song', 'Fantacy', '8.6')
insert into cinema (id, movie, description, rating) values ('5', 'House card', 'Interesting', '9.1')

Table: Cinema

+----------------+----------+
| Column Name    | Type     |
+----------------+----------+
| id             | int      |
| movie          | varchar  |
| description    | varchar  |
| rating         | float    |
+----------------+----------+
id is the primary key for this table.
Each row contains information about the name of a movie, its genre, and its rating.
rating is a 2 decimal places float in the range [0, 10]

 

Write an SQL query to report the movies with an odd-numbered ID and a description that is not "boring".

Return the result table ordered by rating in descending order.

The query result format is in the following example.

 

 입출력 예

 

Example 1:

Input: 
Cinema table:
+----+------------+-------------+--------+
| id | movie      | description | rating |
+----+------------+-------------+--------+
| 1  | War        | great 3D    | 8.9    |
| 2  | Science    | fiction     | 8.5    |
| 3  | irish      | boring      | 6.2    |
| 4  | Ice song   | Fantacy     | 8.6    |
| 5  | House card | Interesting | 9.1    |
+----+------------+-------------+--------+
Output: 
+----+------------+-------------+--------+
| id | movie      | description | rating |
+----+------------+-------------+--------+
| 5  | House card | Interesting | 9.1    |
| 1  | War        | great 3D    | 8.9    |
+----+------------+-------------+--------+
Explanation: 
We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.

 

 Oracle Query

 

select * 
from cinema 
where description!='boring' and mod(id, 2) = 1 
order by rating desc;

* 참고 링크 : https://leetcode.com/problems/not-boring-movies/discuss/1192216/simple-or-100-memory-or-oracle

 

MOD ( ) - 나눈 나머지 값 반환

select mod(3,2)
from dual
-- 결과값: 1

* 참고 링크 : https://devjhs.tistory.com/404, https://20140501.tistory.com/80

 출처

 

https://leetcode.com/problems/not-boring-movies/

Classes More Than 5 Students

 

 문제 설명

 

Table: Courses

Create table If Not Exists Courses (student varchar(255), class varchar(255))
Truncate table Courses
insert into Courses (student, class) values ('A', 'Math')
insert into Courses (student, class) values ('B', 'English')
insert into Courses (student, class) values ('C', 'Math')
insert into Courses (student, class) values ('D', 'Biology')
insert into Courses (student, class) values ('E', 'Math')
insert into Courses (student, class) values ('F', 'Computer')
insert into Courses (student, class) values ('G', 'Math')
insert into Courses (student, class) values ('H', 'Math')
insert into Courses (student, class) values ('I', 'Math')
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| student       | varchar |
| class           | varchar |
+-------------+---------+

(student, class) is the primary key column for this table.
Each row of this table indicates the name of a student and the class in which they are enrolled.

Write an SQL query to report all the classes that have at least five students.

Return the result table in any order.

The query result format is in the following example.

 

5명 이상의 학생이 있는 클래스 쿼리 확인

 

 입출력 예

 

Example 1:

Input: 
Courses table:
+---------+----------+
| student | class    |
+---------+----------+
| A       | Math     |
| B       | English  |
| C       | Math     |
| D       | Biology  |
| E       | Math     |
| F       | Computer |
| G       | Math     |
| H       | Math     |
| I       | Math     |
+---------+----------+
Output: 
+---------+
| class   |
+---------+
| Math    |
+---------+
Explanation: 
- Math has 6 students, so we include it.
- English has 1 student, so we do not include it.
- Biology has 1 student, so we do not include it.
- Computer has 1 student, so we do not include it.

 

 Oracle Query

 

/* Write your PL/SQL query statement below */
select class 
from courses
group by class
having count(distinct student) > 4

* 참고 링크 : https://leetcode.com/problems/classes-more-than-5-students/discuss/927995/Oracle-Solution

  • 5명 이상의 학생이 있는 class 쿼리— having절은 group by와 같이 사용될 수 있음having count(distinct student) > 4having절은 집계함수를 가지고 조건비교를 할 때 사용한다. 집계함수 종류
  • distinct 중복값 처리 (5명 이상의 학생이 중복되는 경우를 having절로 카운트)
  • (5명 이상의 학생이 있는 클래스를 찾는 것이니 class로 묶어줌
  • group by class

 

 출처

 

https://leetcode.com/problems/classes-more-than-5-students/

Big Countries

 

 문제 설명

 

Create table If Not Exists World (name varchar(255), continent varchar(255), area int, population int, gdp int)Truncate table Worldinsert into World (name, continent, area, population, gdp) values ('Afghanistan', 'Asia', '652230', '25500100', '20343000000')insert into World (name, continent, area, population, gdp) values ('Albania', 'Europe', '28748', '2831741', '12960000000')insert into World (name, continent, area, population, gdp) values ('Algeria', 'Africa', '2381741', '37100000', '188681000000')insert into World (name, continent, area, population, gdp) values ('Andorra', 'Europe', '468', '78115', '3712000000')insert into World (name, continent, area, population, gdp) values ('Angola', 'Africa', '1246700', '20609294', '100990000000')

 

able: World

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| name        | varchar |
| continent   | varchar |
| area        | int     |
| population  | int     |
| gdp         | int     |
+-------------+---------+
name is the primary key column for this table.
Each row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value.

 

A country is big if:

  • it has an area of at least three million (i.e., 3000000 km2), or
  • it has a population of at least twenty-five million (i.e., 25000000).

Write an SQL query to report the name, population, and area of the big countries.

Return the result table in any order.

The query result format is in the following example.

 

 입출력 예

 

Example 1:

Input: 
World table:
+-------------+-----------+---------+------------+--------------+
| name        | continent | area    | population | gdp          |
+-------------+-----------+---------+------------+--------------+
| Afghanistan | Asia      | 652230  | 25500100   | 20343000000  |
| Albania     | Europe    | 28748   | 2831741    | 12960000000  |
| Algeria     | Africa    | 2381741 | 37100000   | 188681000000 |
| Andorra     | Europe    | 468     | 78115      | 3712000000   |
| Angola      | Africa    | 1246700 | 20609294   | 100990000000 |
+-------------+-----------+---------+------------+--------------+
Output: 
+-------------+------------+---------+
| name        | population | area    |
+-------------+------------+---------+
| Afghanistan | 25500100   | 652230  |
| Algeria     | 37100000   | 2381741 |
+-------------+------------+---------+

 

 Oracle Query

 

select name, population, area 
from world 
where area >= 3000000 or population >= 25000000;

 

 

 출처

 

https://leetcode.com/problems/big-countries/

Contains Duplicate 

 

 문제 설명

 

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

 

 제한 사항

 

 

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

 

 

 입출력 예

 

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

 

 

 Python 코드

 

Python code 

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(set(nums)) != len(nums)

* 참고 링크 : https://leetcode.com/problems/contains-duplicate/discuss/1159570/Python-99.25-faster

https://leetcode.com/problems/contains-duplicate/discuss/471215/Python-sol-by-native-set-and-length.-run-time-90%2B

 

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
    	hashset = set()
        
        for n in nums:
        	if n in hashset:
            	    return True
        	hashset.add()
        return False

* 참고 링크 : https://www.youtube.com/watch?v=3OamzN90kPg 

 

 C++ 코드

 

C ++ code

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int,bool> map;
        for(size_t i = 0;i<nums.size();++i)
        {
            if(map[nums[i]]==true)
                return true;
            map[nums[i]]=true;
        }
        return false;
    }
};

* 참고 링크 : https://kkminseok.github.io/posts/leetcode_Contains_Duplicate/

 

 출처

 

https://leetcode.com/problems/contains-duplicate/

Consecutive Numbers

 

 문제 설명

 

Create table If Not Exists Employee (id int, name varchar(255), salary int, departmentId int)
Create table If Not Exists Department (id int, name varchar(255))
Truncate table Employee
insert into Employee (id, name, salary, departmentId) values ('1', 'Joe', '70000', '1')
insert into Employee (id, name, salary, departmentId) values ('2', 'Jim', '90000', '1')
insert into Employee (id, name, salary, departmentId) values ('3', 'Henry', '80000', '2')
insert into Employee (id, name, salary, departmentId) values ('4', 'Sam', '60000', '2')
insert into Employee (id, name, salary, departmentId) values ('5', 'Max', '90000', '1')
Truncate table Department
insert into Department (id, name) values ('1', 'IT')
insert into Department (id, name) values ('2', 'Sales')

 

Table: Employee

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| id           | int     |
| name         | varchar |
| salary       | int     |
| departmentId | int     |
+--------------+---------+
id is the primary key column for this table.
departmentId is a foreign key of the ID from the Department table.
Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.

 

Table: Department

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
+-------------+---------+
id is the primary key column for this table.
Each row of this table indicates the ID of a department and its name.

 

 입출력 예

 

Example 1:

Input: 
Employee table:
+----+-------+--------+--------------+
| id | name  | salary | departmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Jim   | 90000  | 1            |
| 3  | Henry | 80000  | 2            |
| 4  | Sam   | 60000  | 2            |
| 5  | Max   | 90000  | 1            |
+----+-------+--------+--------------+
Department table:
+----+-------+
| id | name  |
+----+-------+
| 1  | IT    |
| 2  | Sales |
+----+-------+
Output: 
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Jim      | 90000  |
| Sales      | Henry    | 80000  |
| IT         | Max      | 90000  |
+------------+----------+--------+

Explanation: Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.

 Oracle Query

 

select
D.Name as Department, E.Name as Employee, Salary
from Employee E inner join Department D
on E.DepartmentID = D.ID
where Salary = (select max(Salary)
                from Employee
                where E.DepartmentID = DepartmentID);

* 참고 링크 : https://leetcode.com/problems/department-highest-salary/discuss/1064441/Most-Efficient-Oracle-solution

 

 출처

 

https://leetcode.com/problems/department-highest-salary/

Prime Number of Set Bits in Binary Representation

 

 문제 설명

 

Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.

Recall that the number of set bits an integer has is the number of 1's present when written in binary.

  • For example, 21 written in binary is 10101, which has 3 set bits.
왼쪽과 오른쪽 두 개의 정수가 주어지면 이진 표현에 소수의 세트 비트를 갖는 포함 범위[좌, 우]의 숫자 카운트를 반환합니다.

정수가 갖는 세트 비트의 수는 이진수로 쓸 때 존재하는 1의 수라는 것을 기억하라.

예를 들어, 이진법으로 작성된 21은 10101이고, 3개의 세트 비트를 가지고 있다.

 

 제한 사항

 

  • 1 <= left <= right <= 106
  • 0 <= right - left <= 104

 

 입출력 예

 

Example 1:

Input: left = 6, right = 10
Output: 4
Explanation:
6  -> 110 (2 set bits, 2 is prime)
7  -> 111 (3 set bits, 3 is prime)
8  -> 1000 (1 set bit, 1 is not prime)
9  -> 1001 (2 set bits, 2 is prime)
10 -> 1010 (2 set bits, 2 is prime)
4 numbers have a prime number of set bits.

Example 2:

Input: left = 10, right = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
5 numbers have a prime number of set bits.

 

 Python 코드

 

Python code 

class Solution:
    def countPrimeSetBits(self, L: int, R: int) -> int:
        return sum(bin(i).count('1') in [2,3,5,7,11,13,17,19] for i in range(L, R+1))

bin(i).count('1') # 이진 표현에서 1의 수가 소수인 경우

bin(i).count('1') in [2, 3, 4, 5, 7, 11, 13, 17, 19]  

# 이진 표현에서 1의 수가 [2, 3, 4, 5, 7, 11, 13, 17, 19]에 빈도가 있는 경우

sum(bin(i).count('1') in [2, 3, 5, 7, 11, 13, 17, 19] for i in range(L, R+1))

# sum( ) 함수를 이용하여 count를 증가시킨다.

 

* 참고 링크 1 : https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/801535/Python-3-One-Line

 

 

 C++ 코드

 

C ++ code

// c++ code
#include <cmath>
class Solution {
public:
    int countPrimeSetBits(int L, int R) {
        int res = 0;
        for (int num = L; num <= R; num++) {
            int count = countOne(num);
            if (isPrime(count))
                res++;
        }
        return res;
    }
    
    bool isPrime(int num) {
        if (num <= 3)
            return num > 1;
        
        int square_root = sqrt(num);
        for (int i = 2; i <= square_root; i++) {
            if (num % i == 0)
                return false;
        }
        return true;
    }
    
    int countOne(int num) {
        vector<int> bin = dec2bin(num);
        int count = 0;
        for (auto i = bin.begin(); i < bin.end(); i++) {
            if (*i == 1)
                count++;
        }
        return count;
    }
    
    vector<int> dec2bin(int num) {
        vector<int> bin;
        while (num != 0) {
            bin.push_back(num % 2);
            num /= 2;
        }
        reverse(bin.begin(), bin.end());
        return bin;
    }
};

* 참고 링크 : https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/376499/C%2B%2B-and-Python-3-bad-performance-need-to-improve

 

 출처

 

https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/

Power of Four

 

 문제 설명

 

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4x.

 

 제한 사항

 

  • -231 <= n <= 231 - 1

 

 입출력 예

 

Example 1:

Input: n = 16
Output: true

Example 2:

Input: n = 5
Output: false

Example 3:

Input: n = 1
Output: true

 

 

 Python 코드

 

Python code 

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        return math.log(n, 1/4) % 1 == 0 if n > 0 else False

* 참고 링크 : https://leetcode.com/problems/power-of-four/discuss/637372/Python-3-Single-line

  • math.log( ) 함수 이용 // loops(반복문) 또는 recursion(재귀)를 피하는 방법 중 하나// x : 필수의 로그를 계산할 값을 지정// base : 선택적으로 사용할 로그 베이스 (Default 값 : e)
  • ( 값이 0 또는 음수이면 ValueError 반환, 값이 숫자가 아니면 TypeError를 반환)
  • math.log(x, base)

 

 C++ 코드

 

C ++ code

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
    }
};

* 참고 링크 : https://leetcode.com/problems/power-of-four/discuss/80460/1-line-C%2B%2B-solution-without-confusing-bit-manipulations

 

 출처

 

https://leetcode.com/problems/power-of-four/

Design Circular Queue

 

 문제 설명

 

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

Implementation the MyCircularQueue class:

  • MyCircularQueue(k) Initializes the object with the size of the queue to be k.
  • int Front() Gets the front item from the queue. If the queue is empty, return -1.
  • int Rear() Gets the last item from the queue. If the queue is empty, return -1.
  • boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.
  • boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.
  • boolean isEmpty() Checks whether the circular queue is empty or not.
  • boolean isFull() Checks whether the circular queue is full or not.

You must solve the problem without using the built-in queue data structure in your programming language. 

 

 제한 사항

 

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.

 

 입출력 예

 

Example 1:

Input
["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
Output
[null, true, true, true, false, 3, true, true, true, 4]

Explanation
MyCircularQueue myCircularQueue = new MyCircularQueue(3);
myCircularQueue.enQueue(1); // return True
myCircularQueue.enQueue(2); // return True
myCircularQueue.enQueue(3); // return True
myCircularQueue.enQueue(4); // return False
myCircularQueue.Rear();     // return 3
myCircularQueue.isFull();   // return True
myCircularQueue.deQueue();  // return True
myCircularQueue.enQueue(4); // return True
myCircularQueue.Rear();     // return 4

 

 Python 코드

 

Python code 

class MyCirculurQueue:
    def __init__(self, k):
        self.q = [None] * k
        self.maxlen = k
        self.p1 = 0
        self.p2 = 0

    # enQueue(): rear 포인터 이동
    def enQueue(self, value):
        if self.q[self.p2] is None:
            self.q[self.p2] = value
            self.p2 = (self.p2 + 1) % self.maxlen
            return True
        else:
            return False

    # deQueue(): front 포인터 이동
    def deQueue(self):
        if self.q[self.p1] is None:
            return False
        else:
            self.q[self.p1] = None
            self.p1 = (self.p1 + 1) % self.maxlen
            return True

    def Front(self):
        return -1 if self.q[self.p1] is None else self.q[self.p1]

    def Rear(self):
        return -1 if self.q[self.p2 - 1] is None else self.q[self.p2 - 1]

    def isEmpty(self):
        return self.p1 == self.p2 and self.q[self.p1] is None

    def isFull(self):
        return self.p1 == self.p2 and self.q[self.p1] is not None

* 참고 링크 : https://deep-learning-study.tistory.com/480

 

 C++ 코드

 

C ++ code


class MyCircularQueue {
public:
  MyCircularQueue(int k): q_(k) {}
  
  bool enQueue(int value) {
    if (isFull()) return false;
    q_[(head_ + size_) % q_.size()] = value;    
    ++size_;
    return true;
  }
  
  bool deQueue() {
    if (isEmpty()) return false;
    head_ = (head_ + 1) % q_.size();
    --size_;
    return true;
  }
 
  int Front() { return isEmpty() ? -1 : q_[head_]; }
 
  int Rear() { return isEmpty() ? -1 : q_[(head_ + size_ - 1) % q_.size()]; }
 
  bool isEmpty() { return size_ == 0; }
 
  bool isFull() { return size_ == q_.size(); }
private:
  vector<int> q_;
  int head_ = 0;
  int size_ = 0;
};

* 참고 링크 : https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/

 

 출처

 

https://leetcode.com/problems/design-circular-queue/

Implement Queue using Stacks

 

 문제 설명

 

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

 

 제한 사항

 

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.
  • All the calls to pop and peek are valid.

 

 입출력 예

 

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

 

 Python 코드

 

Python code 

class MyQueue: 
	def __init__(self): 
		// 문제에서 2개의 스택을 사용하라고 하니, 배열을 2개를 사용
		self.stack1 = [] 
		self.stack2 = [] 
		
	def push(self, x: int): 
		// stack1에는 push 데이터를 넣어줌
		self.stack1.append(x) 
		
	def pop(self): 
	// pop을 할때에는 stack1의 배열을 거꾸로 변경하는 과정이 필요
	// pop을 할때, stack1.pop()을 하여, stack2에 넣어줌
	// stack1 [1, 2, 3] -> stack2 = [3, 2, 1] 
		self.peek() 
		return self.stack2.pop() 
		
	def peek(self): 
		// peek는 큐의 첫번째 값을 가져와야 하므로 
		// stack1의 모든 값을 거꾸로 stack2에 넣어서, stack2[-1]을 리턴
		
		if not self.stack2: 
		// stack1의 모든 값이 나올때까지 해주는데, 
		// stack2가 비어있지 않은 경우에 stack2에 값을 넣을 경우 
		// pop()이 힘들어지니 stack1을 그대로 이용
		
		// 1) stack1 [1, 2, 3] -> stack2 [3, 2, 1] 
		// 2) MyQueue.push(4) 
		// 3) stack1 -> [4] , stack2 [3, 2, 1] 의 경우 
		// stack1의 값을 넣어주면 stack2는, [3, 2, 1, 4]가 되므로 pop을 하기가 힘듬 
		// 4) stack1의 [4]는 어차피 stack2가 다 빌때까지 필요없으므로 
		// 그냥 stack2가 빌때까지 stack1에 넣어둠 
		
			while self.stack1: 
				self.stack2.append(self.stack1.pop()) 
		return self.stack2[-1] 
		
		
	def empty(self): 
		return (len(self.stack1) == 0) and (len(self.stack2) == 0)

* 참고 링크 : https://jasmine46.tistory.com/71

 

 C++ 코드

 

C ++ code

// Time:  O(1), amortized
// Space: O(n)

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        A_.emplace(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        peek();
        B_.pop();
    }

    // Get the front element.
    int peek(void) {
        if (B_.empty()) {
          // Transfers the elements in A_ to B_.
          while (!A_.empty()) {
            B_.emplace(A_.top());
            A_.pop();
          }
        }
        if (B_.empty()) {  // B_ is still empty!
          throw length_error("empty queue");
        }
        return B_.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return A_.empty() && B_.empty();
    }

 private:
  stack<int> A_, B_;
};

* 참고 링크 : https://shareablecode.com/snippets/implement-queue-using-stacks-c-solution-leetcode-FaBa-R43B

 

 출처

 

https://leetcode.com/problems/implement-queue-using-stacks/

Implement Stack using Queues

 

 문제 설명

 

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

  • void push(int x) Pushes element x to the top of the stack.
  • int pop() Removes the element on the top of the stack and returns it.
  • int top() Returns the element on the top of the stack.
  • boolean empty() Returns true if the stack is empty, false otherwise.

Notes:

  • You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.

 

 제한 사항

 

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, top, and empty.
  • All the calls to pop and top are valid.

 

 입출력 예

 

Example 1:

Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

 Python 코드

 

Python code 

class MyStack:

    def __init__(self):
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)

    def pop(self) -> int:
        for i in range(len(self.q) - 1):
            self.push(self.q.popleft())
        return self.q.popleft()

    def top(self) -> int:
        return self.q[-1]

    def empty(self) -> bool:
        return len(self.q) == 0

# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

* 참고 링크 : https://www.youtube.com/watch?v=rW4vm0-DLYc 

 

 C++ 코드

 

C ++ code

class MyStack {
    queue<int>q;
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) 
    {
        q.push(x);
        for (int i=0; i<q.size()-1; i++)
        {
            q.push(q.front());
            q.pop();
        }        
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() 
    {
        int result=q.front();
        q.pop();
        return result;
    }
    
    /** Get the top element. */
    int top() 
    {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() 
    {
        return q.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * bool param_4 = obj.empty();
 */

* 참고 링크 : https://github.com/wisdompeak/LeetCode/blob/master/Stack/225.Implement-Stack-using-Queues/225.Implement%20Stack%20using%20Queues.cpp

 

 출처

 

https://leetcode.com/problems/implement-stack-using-queues/submissions/

+ Recent posts