ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Algorithm] ์ด์ง„ํƒ์ƒ‰(Binary Search)
    ๐Ÿ’ปProgramming/Algorithm 2024. 4. 9. 15:15

    ์ด์ง„ํƒ์ƒ‰์ด๋ž€?

    "์ •๋ ฌ๋˜์–ด ์žˆ๋Š” ๋ฐ์ดํ„ฐ"์—์„œ ํŠน์ •ํ•œ ๊ฐ’์„ ์ฐพ์•„๋‚ด๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค.

     

    ๋ฌธ์ œ

    ์ž„์˜์˜ N๊ฐœ์˜ ์ˆซ์ž๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. N๊ฐœ์˜ ์ˆ˜๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ๋‹ค์Œ N๊ฐœ์˜ ์ˆ˜ ์ค‘ ํ•œ ๊ฐœ์˜ ์ˆ˜์ธ M์ด ์ฃผ์–ด์ง€๋ฉด
    ์ด๋ถ„๊ฒ€์ƒ‰์œผ๋กœ M์ด ์ •๋ ฌ๋œ ์ƒํƒœ์—์„œ ๋ช‡ ๋ฒˆ์งธ์— ์žˆ๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”. ๋‹จ ์ค‘๋ณต๊ฐ’์€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

    ์ž…๋ ฅ

    ์ฒซ ์ค„์— ํ•œ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=1,000,000)๊ณผ M์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.
    ๋‘ ๋ฒˆ์งธ ์ค„์— N๊ฐœ์˜ ์ˆ˜๊ฐ€ ๊ณต๋ฐฑ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

    ์ถœ๋ ฅ

    ์ฒซ ์ค„์— ์ •๋ ฌ ํ›„ M์˜ ๊ฐ’์˜ ์œ„์น˜ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

     

    ์ด์ง„ํƒ์ƒ‰์˜ ๊ณผ์ •

    1. ์ผ๋‹จ ๋ฐฐ์—ด์„ ์ •๋ ฌํ•œ๋‹ค. (์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ)

    2. ๋‹ต์ด ๋  ์ˆ˜ ์žˆ๋Š” ์ตœ์†Œ๊ฐ’๊ณผ ์ตœ๋Œ€๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ ๊ตฌํ•œ๋‹ค. (์œ„์˜ ๋ฌธ์ œ์—์„œ๋Š” ์ตœ์†Œ๊ฐ’์ด ๊ฐ€์žฅ ์ž‘์€ ์ธ๋ฑ์Šค๊ฐ€ ๋˜๊ณ , ์ตœ๋Œ€๊ฐ’์ด ๊ฐ€์žฅ ํฐ ์ธ๋ฑ์Šค๊ฐ€ ๋  ๊ฒƒ์ด๋‹ค.)

    3. ๊ทธ๋ฆฌ๊ณ  (์ตœ์†Œ๊ฐ’ + ์ตœ๋Œ€๊ฐ’) / 2 ์˜ ์ค‘๊ฐ„๊ฐ’์„ ๋งŒ๋“ ๋‹ค. ๋งŒ์•ฝ ์ด ์ค‘๊ฐ„ ์ธ๋ฑ์Šค์˜ ๊ฐ’์ด M๋ณด๋‹ค ํฌ๋‹ค๋ฉด ์ตœ๋Œ€๊ฐ’์„ ์ด ์ค‘๊ฐ„๊ฐ’ - 1์œผ๋กœ ๋ฐ”๊พผ๋‹ค.

    ๋˜, ๋งŒ์•ฝ ์ค‘๊ฐ„ ์ธ๋ฑ์Šค์˜ ๊ฐ’์ด M๋ณด๋‹ค ์ž‘๋‹ค๋ฉด, ์ตœ์†Œ๊ฐ’์„ ์ค‘๊ฐ„๊ฐ’ + 1๋กœ ๋ฐ”๊พผ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ด๊ฒƒ์„ ์ตœ์†Ÿ๊ฐ’์ด ์ตœ๋Œ“๊ฐ’๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์„ ๋™์•ˆ๋งŒ ๊ณ„์† ๋ฐ˜๋ณตํ•œ๋‹ค.

     

    ๊ตฌํ˜„ ์ฝ”๋“œ

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Section6_8_MyVer {
        int solution(int n, int m, int[] list) {
            int low = 0;
            int high = n - 1;
            int mid = (low + high) / 2;
            Arrays.sort(list);
            while (low <= high) {
                mid = (low + high) / 2;
                if (list[mid] > m)  high = mid - 1;
                else if (list[mid] == m)    break;
                else    low = mid + 1;
            }
    
            return mid + 1;
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            Section6_8_MyVer T = new Section6_8_MyVer();
            int n = scanner.nextInt();
            int m = scanner.nextInt();
            int[] list = new int[n];
            for (int i = 0; i < n; i++) list[i] = scanner.nextInt();
            System.out.println(T.solution(n, m, list));
        }
    }

     

    ์ด์ง„ํƒ์ƒ‰์˜ ์‹œ๊ฐ„๋ณต์žก๋„

    O(logn)

    ๋ฐฐ์—ด์˜ ํฌ๊ธฐ์— ๋น„ํ•˜์—ฌ ์‹คํ–‰ ์‹œ๊ฐ„์ด ๋น ๋ฅด๋‹ค. -> ๋Œ€์šฉ๋Ÿ‰ ๋ฐ์ดํ„ฐ์—์„œ ํŠน์ • ๊ฐ’์˜ ์œ„์น˜๋ฅผ ์ฐพ๋Š” ๋ฐ ์šฉ์ดํ•˜๋‹ค. 

Designed by Tistory.