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/

Consecutive Numbers

 

 문제 설명

 

Table: Logs

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+
id is the primary key for this table.

 

Write an SQL query to find all numbers that appear at least three times consecutively.

Return the result table in any order.

The query result format is in the following example.

 

 입출력 예

 

Example 1:

Input: 
Logs table:
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+
Output: 
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+
Explanation: 1 is the only number that appears consecutively for at least three times.

 

 Oracle Query

 

SELECT DISTINCT 
	l1.Num As ConsecutiveNums
FROM Logs l1
JOIN Logs l2 ON l1.Id = l2.Id-1
JOIN Logs l3 ON l2.Id = l3.Id-1
WHERE l1.Num = l2.Num
	AND l2.Num = l3.Num;

* 참고 링크 : https://leetcode.com/problems/consecutive-numbers/discuss/185886/Self-Join-Twice-(681-ms-faster-than-100.00-of-Oracle-online-submissions-for-Consecutive-Numbers.)

 

 출처

 

https://leetcode.com/problems/consecutive-numbers/

Valid Triangle Number

 

 문제 설명

 

Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

 

 제한 사항

 

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000

 

 입출력 예

 

Example 1:

Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are: 
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

Example 2:

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

 

 Python 코드

 

Python code 

class Solution(object):
    def triangleNumber(self, nums):

        nums, count, n = sorted(nums, reverse=1), 0, len(nums)
        for i in range(n):
            j, k = i + 1, n - 1
            while j < k:
                if nums[j] + nums[k] > nums[i]:
                    count += k - j
                    j += 1
                else:
                    k -= 1
        return count

* 참고 링크 : https://leetcode.com/problems/valid-triangle-number/discuss/104177/O(N2)-solution-for-C%2B%2B-and-Python

 

 C++ 코드

 

C ++ code

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        if(nums.size() < 3) return 0;
        sort(nums.begin(), nums.end(), greater<int>());
        int res = 0;
        int n = nums.size();
        for(int a = 0; a < n-2; ++a){
            int b = a+1;
            int c = n-1;
            while(b < c){
                if(nums[b] + nums[c] > nums[a]){
                    res = res + c - b;
                    ++b;
                }
                else
                    --c;
            }
        }
        return res;
    }
};

* 참고 링크 : https://www.programmerall.com/article/1415760413/

 

 출처

 

https://leetcode.com/problems/valid-triangle-number/

Find Peak Element

 

 문제 설명

 

A peak element is an element that is strictly greater than its neighbors.

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞.

You must write an algorithm that runs in O(log n) time.

 

 제한 사항

 

  • 1 <= nums.length <= 1000
  • -231 <= nums[i] <= 231 - 1
  • nums[i] != nums[i + 1] for all valid i.

 

 입출력 예

 

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

 

 Python 코드

 

Python code 

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        left = 0
        right = len(nums)-1
				# left가 커지고 right가 작아지는 경우 left와 right가 같아질 수 있다.
        # 그 때 원한느 값을 찾은 경우이므로 left와 right가 같아지면 반복문 종료
        while left < right:
            mid = (left + right) // 2      # 가운데 지점
            if nums[mid] < nums[mid+1]:    # 현재 값이 오른쪽 값보다 작다면
                left = mid+1
            else:                          # 현재 값이 오른쪽 값보다 크다면
                right = mid
        return left                        # 반복문이 종료되면 left가 정답

* 참고 링크 : https://velog.io/@hrpp1300/LeetCode-162.-Find-Peak-Element

 

 C++ 코드

 

C ++ code

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int left = 0;
        int right = nums.size() - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > nums[mid + 1]) {
                right = mid;
            }
            else {
                left = mid + 1;
            }
        }
        return left; 
    }
};

* 참고 링크 : https://myeongcs.tistory.com/80

 

 출처

 

https://leetcode.com/problems/find-peak-element/submissions/

Same Tree

 

 문제 설명

 

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

  • -1: Your guess is higher than the number I picked (i.e. num > pick).
  • 1: Your guess is lower than the number I picked (i.e. num < pick).
  • 0: your guess is equal to the number I picked (i.e. num == pick).

Return the number that I picked.

 

 제한 사항

 

  • 1 <= n <= 231 - 1
  • 1 <= pick <= n

 

 입출력 예

 

Example 1:

Input: n = 10, pick = 6
Output: 6

Example 2:

Input: n = 1, pick = 1
Output: 1

Example 3:

Input: n = 2, pick = 1
Output: 1

 

 

 Python 코드

 

Python code 

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:

class Solution: 
    def guessNumber(self, n: int) -> int: 
        left, right = 1, n 
        
        while True: 
            middle_num = int((left + right) / 2) 
            if guess(middle_num) == 1: 
                left = middle_num + 1 
            elif guess(middle_num) == -1: 
                right = middle_num - 1 
            else: 
                return middle_num

* 참고 링크 : https://somjang.tistory.com/entry/leetCode-374-Guess-Number-Higher-or-Lower-Python

 

 C++ 코드

 

C ++ code

//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Guess Number Higher or Lower.
//Memory Usage: 7.3 MB, less than 100.00% of C++ online submissions for Guess Number Higher or Lower.

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        int left = 1, right = n, cur = left+(right-left)/2;

        while(true){
            switch(guess(cur)){
                case -1:
                    right = cur-1;
                    cur = left+(right-left)/2;
                    break;
                case 1:
                    left = cur+1;
                    cur = left+(right-left)/2;
                    break;
                case 0:
                    return cur;
            }
        }
        return 0;
    }
};

* 참고 링크 : https://github.com/keineahnung2345/leetcode-cpp-practices/blob/master/374.%20Guess%20Number%20Higher%20or%20Lower.cpp

 

 출처

 

https://leetcode.com/problems/guess-number-higher-or-lower/

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/

+ Recent posts