01-09 04:37
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_50 ์ด๋ถ„๊ฒ€์ƒ‰ ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_50 ์ด๋ถ„๊ฒ€์ƒ‰

miinsun 2022. 1. 13. 15:09

 

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

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

 

 

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

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

๋‘ ๋ฒˆ์งธ ์ค„์— N๊ฐœ์˜ ์ˆ˜๊ฐ€ ๊ณต๋ฐฑ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

8 32
23 87 65 12 57 32 99 81

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

3

 

 

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	
	public int solution(int n, int key, int[] arr) {
		int answer = 0;
		
		Arrays.sort(arr);
		
		for(int i = 0; i < n; i++) {
			if(arr[i] == key) {
				answer = i + 1;
				break;
			}
		}
		
		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 ;
	}
}

 

 

์ด๋ถ„ ๊ฒ€์ƒ‰ Version

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