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

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_27 ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_27 ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด

miinsun 2022. 1. 4. 12:51

 

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

N๊ฐœ์˜ ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.
์ด ์ˆ˜์—ด์—์„œ ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ์ด ํŠน์ • ์ˆซ์ž M์ด ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋ช‡ ๋ฒˆ ์žˆ๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

๋งŒ์•ฝ N=8, M=6์ด๊ณ  ์ˆ˜์—ด์ด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค๋ฉด
1 2 1 3 1 1 1 2
ํ•ฉ์ด 6์ด ๋˜๋Š” ์—ฐ์†๋ถ€๋ถ„์ˆ˜์—ด์€ {2, 1, 3}, {1, 3, 1, 1}, {3, 1, 1, 1}๋กœ ์ด 3๊ฐ€์ง€์ž…๋‹ˆ๋‹ค.

 

 

 

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

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

์ˆ˜์—ด์˜ ์›์†Œ๊ฐ’์€ 1,000์„ ๋„˜์ง€ ์•Š๋Š” ์ž์—ฐ์ˆ˜์ด๋‹ค.

8 6
1 2 1 3 1 1 1 2

์ถœ๋ ฅ - ์ฒซ์งธ ์ค„์— ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 
3

 

 

โ€‹

๐Ÿ’ป Solution.java

๋‹ต์•ˆ 1) 2์ค‘ for๋ฌธ์œผ๋กœ ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ์ข‹์ง€ ๋ชปํ•จ

import java.util.*;

public class Main {
	public int solution(int n, int m, int[] arr) {
		int answer = 0, sum = 0;
		
		for(int i = 1; i <= n; i++) {
			for(int j = 0; j < n; j++) {
				if(j + i > n)
					break;
				for(int k = j; k < j + i; k++) {
					sum += arr[k];
				}
				System.out.println();
				if(sum == m)
					answer++;
				
				sum = 0;
			}
		}
		
        return answer;
	}

public static void main(String[] args){
		Main main  = new Main();
		Scanner sc =new Scanner(System.in);
		
		int n = sc.nextInt();
		int m = sc.nextInt();

		int[] arr = new int[n];
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		
		System.out.println(main.solution(n, m, arr));
		
		sc.close();
		return ;
	}
}

๋‹ต์•ˆ 2) two pointer๋กœ ์‹œ๊ฐ„๋ณต์žก๋„ O(n)์œผ๋กœ ํ•ด๊ฒฐ

import java.util.*;

public class Main {

	public int solution(int n, int m, int[] arr) {
		int answer = 0, sum = 0; 
		int lt = 0;
		
		for(int rt = 0; rt < n; rt++) {
			sum += arr[rt];
			if(sum == m) answer++;
			
			while(sum >= m) {
				sum -= arr[lt++];
				if(sum == m) answer++;
			}
		}
		
        	return answer;
	}
   
	public static void main(String[] args){
		Main main  = new Main();
		Scanner sc =new Scanner(System.in);
		
		int n = sc.nextInt();
		int m = sc.nextInt();

		int[] arr = new int[n];
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		
		System.out.println(main.solution(n, m, arr));
		
		sc.close();
		return ;
	}
}

 

Comments