C# 1920번 수 찾기

2022. 2. 24. 15:22C#/[백준]이분 탐색

문제

시간초과 코드 :

using System;
using System.Linq;
using System.Text;
namespace _1
{
    class Program
    {
        static void Main(string[] args)
        {
            int N = Convert.ToInt32(Console.ReadLine());
            int[] A = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            int M = Convert.ToInt32(Console.ReadLine());
            int[] A2 = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < M; i++)
            {

                sb.AppendLine(Array.Exists(A, x => x == A2[i]) ? "1" : "0");
                
            }
            Console.WriteLine(sb);
        }
    }
}

혹시 이분탐색을 사용하지 않고 하나하나 찾아도 될지 시도해봤으나 역시나 시간초과가 뜬다.

그래서 이분탐색을 알아보니 C#에는 이분탐색이 기본적으로 탑재되어 있어 이 메소드를 활용했다.

코드 :

using System;
using System.Linq;
using System.Text;
namespace _1
{
    class Program
    {
        static int N = Convert.ToInt32(Console.ReadLine());
        static int[] A = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
        static int M = Convert.ToInt32(Console.ReadLine());
        static int[] M_Array = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
        static StringBuilder sb = new StringBuilder();

        static public void BinarySearch()
        {
            
            Array.Sort(A); // A = {1 2 3 4 5}
            for (int i = 0; i < M; i++)
            {
                int index = Array.BinarySearch(A, M_Array[i]);
                if(index < 0)
                {
                    sb.AppendLine("0");
                }
                else
                {
                    sb.AppendLine("1");
                }

            }

        }
        static void Main(string[] args)
        {
            BinarySearch();
            Console.WriteLine(sb);
        }
    }
}

Array.BinarySearch()를 활용하면 된다.

'C# > [백준]이분 탐색' 카테고리의 다른 글

C# 2110번 공유기 설치  (0) 2022.02.24
C# 2805번 나무 자르기  (0) 2022.02.24
C# 1654번 랜선 자르기  (0) 2022.02.24
C# 10816번 숫자 카드2  (0) 2022.02.24