01-08 08:57
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_51 ๋ฎค์ง ๋น„๋””์˜ค(๊ฒฐ์ • ์•Œ๊ณ ๋ฆฌ์ฆ˜) ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_51 ๋ฎค์ง ๋น„๋””์˜ค(๊ฒฐ์ • ์•Œ๊ณ ๋ฆฌ์ฆ˜)

miinsun 2022. 1. 13. 16:35

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

์ง€๋‹ˆ๋ ˆ์ฝ”๋“œ์—์„œ๋Š” ๋ถˆ์„ธ์ถœ์˜ ๊ฐ€์ˆ˜ ์กฐ์˜ํ•„์˜ ๋ผ์ด๋ธŒ ๋™์˜์ƒ์„ DVD๋กœ ๋งŒ๋“ค์–ด ํŒ๋งคํ•˜๋ ค ํ•œ๋‹ค.

DVD์—๋Š” ์ด N๊ฐœ์˜ ๊ณก์ด ๋“ค์–ด๊ฐ€๋Š”๋ฐ, DVD์— ๋…นํ™”ํ•  ๋•Œ์—๋Š” ๋ผ์ด๋ธŒ์—์„œ์˜ ์ˆœ์„œ๊ฐ€ ๊ทธ๋Œ€๋กœ ์œ ์ง€๋˜์–ด์•ผ ํ•œ๋‹ค.
์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋Š” ๊ฒƒ์„ ์šฐ๋ฆฌ์˜ ๊ฐ€์ˆ˜ ์กฐ์˜ํ•„์”จ๊ฐ€ ๋งค์šฐ ์‹ซ์–ดํ•œ๋‹ค. ์ฆ‰, 1๋ฒˆ ๋…ธ๋ž˜์™€ 5๋ฒˆ ๋…ธ๋ž˜๋ฅผ ๊ฐ™์€ DVD์— ๋…นํ™”ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” 1๋ฒˆ๊ณผ 5๋ฒˆ ์‚ฌ์ด์˜ ๋ชจ๋“  ๋…ธ๋ž˜๋„ ๊ฐ™์€ DVD์— ๋…นํ™”ํ•ด์•ผ ํ•œ๋‹ค. ๋˜ํ•œ ํ•œ ๋…ธ๋ž˜๋ฅผ ์ชผ๊ฐœ์„œ ๋‘ ๊ฐœ์˜ DVD์— ๋…นํ™”ํ•˜๋ฉด ์•ˆ๋œ๋‹ค.

์ง€๋‹ˆ๋ ˆ์ฝ”๋“œ ์ž…์žฅ์—์„œ๋Š” ์ด DVD๊ฐ€ ํŒ”๋ฆด ๊ฒƒ์ธ์ง€ ํ™•์‹ ํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์ด ์‚ฌ์—…์— ๋‚ญ๋น„๋˜๋Š” DVD๋ฅผ ๊ฐ€๊ธ‰์  ์ค„์ด๋ ค๊ณ  ํ•œ๋‹ค. ๊ณ ๋ฏผ ๋์— ์ง€๋‹ˆ๋ ˆ์ฝ”๋“œ๋Š” M๊ฐœ์˜ DVD์— ๋ชจ๋“  ๋™์˜์ƒ์„ ๋…นํ™”ํ•˜๊ธฐ๋กœ ํ•˜์˜€๋‹ค. ์ด ๋•Œ DVD์˜ ํฌ๊ธฐ(๋…นํ™” ๊ฐ€๋Šฅํ•œ ๊ธธ์ด)๋ฅผ ์ตœ์†Œ๋กœ ํ•˜๋ ค๊ณ  ํ•œ๋‹ค.

๊ทธ๋ฆฌ๊ณ  M๊ฐœ์˜ DVD๋Š” ๋ชจ๋‘ ๊ฐ™์€ ํฌ๊ธฐ์—ฌ์•ผ ์ œ์กฐ์›๊ฐ€๊ฐ€ ์ ๊ฒŒ ๋“ค๊ธฐ ๋•Œ๋ฌธ์— ๊ผญ ๊ฐ™์€ ํฌ๊ธฐ๋กœ ํ•ด์•ผ ํ•œ๋‹ค.

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N(1≤N≤1,000), M(1≤M≤N)์ด ์ฃผ์–ด์ง„๋‹ค.

๋‹ค์Œ ์ค„์—๋Š” ์กฐ์˜ํ•„์ด ๋ผ์ด๋ธŒ์—์„œ ๋ถ€๋ฅธ ์ˆœ์„œ๋Œ€๋กœ ๋ถ€๋ฅธ ๊ณก์˜ ๊ธธ์ด๊ฐ€ ๋ถ„ ๋‹จ์œ„๋กœ(์ž์—ฐ์ˆ˜) ์ฃผ์–ด์ง„๋‹ค.

๋ถ€๋ฅธ ๊ณก์˜ ๊ธธ์ด๋Š” 10,000๋ถ„์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์ž.

9 3
1 2 3 4 5 6 7 8 9

์ถœ๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ DVD์˜ ์ตœ์†Œ ์šฉ๋Ÿ‰ ํฌ๊ธฐ๋ฅผ ์ถœ๋ ฅํ•˜์„ธ์š”.

17

 

 

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	
	public int solution(int n, int key, int[] arr) {
		int answer = 0;
		Arrays.sort(arr);
		int lt = 0, rt = n - 1;
        
        while(lt <= rt){
        	int mid = (lt + rt) / 2;
            if (arr[mid] == key){
            	answer = mid + 1;
                break;
            }
            if(arr[mid] > key) rt = mid - 1;
            else lt = mid + 1;
        }
		
		return answer;
	}
	
	public static void main(String[] args){
		Main main = new Main();
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		int key = sc.nextInt();
		
		int [] arr = new int [n];
		
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		
		System.out.println(main.solution(n, key, arr));
		
		sc.close();
		return ;
	}
}

 

 

 

Comments