- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/178870
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/178870. 연속된 부분 수열의 합
풀이 시간 : 20분
import java.util.*;
class Solution {
public int[] solution(int[] sequence, int k) {
int[] answer = {};
int minLength = Integer.MAX_VALUE;
for(int i=0; i<sequence.length; i++){
int sum = 0;
for(int j=0; j<sequence.length; j++){
sum += sequence[j];
if(sum == k){
if( j - i + 1 < minLength){
minLength = j - i + 1;
answer = new int[minLength];
System.arraycopy(sequence, i, answer, 0, minLength);
}
}
break;
}
}
return answer;
}
}
//before
for(int i=0; i<sequence.length; i++){
int sum = 0;
for(int j=0; j<sequence.length; j++){
sum += sequence[j];
if(sum == k){
if( j - i + 1 < minLength){
minLength = j - i + 1;
answer = new int[minLength];
System.arraycopy(sequence, i, answer, 0, minLength);
}
}
break;
}
}
return answer;
//ing
for(int i=0; i<sequence.length; i++){
int sum = 0;
for(int j=i; j<sequence.length; j++){
sum += sequence[j];
if(sum == k){
if( j - i + 1 < minLength){
minLength = j - i + 1;
start = i;
end = j;
answer = new int[]{start, end};
}
break;
}
}
}
if(start == -1){
return new int[0];
}
//after
int[] answer = new int[0];
int minLength = Integer.MAX_VALUE;
int start = -1;
int end = -1;
for(int i=0; i<sequence.length; i++){
int sum = 0;
for(int j=i; j<sequence.length; j++){
sum += sequence[j];
if(sum == k){
if( j - i + 1 < minLength){
minLength = j - i + 1;
start = i;
end = j;
answer = new int[]{start, end};
}
break;
}
}
}
return answer;
int[] answer = new int[0];
int minLength = Integer.MAX_VALUE;
int start = -1;
int end = -1;
int sum = 0;
int i = 0;
int j = 0;
while(j < sequence.length){
sum += sequence[j++];
while(sum > k && i < j){
sum -= sequence[i++];
}
if(sum == k){
if(j - i < minLength){
minLength = j - i;
start = i;
end = j - 1;
}
}
}
answer = new int[]{start, end};
return answer;
}
}
풀이 시간 : 1시간 7분(첫 풀이 시간 포함)
import java.util.*;
class Solution {
public int[] solution(int[] sequence, int k) {
int[] answer = new int[0];
int minLength = Integer.MAX_VALUE;
int start = -1;
int end = -1;
int sum = 0;
int i = 0;
int j = 0;
while(j < sequence.length){
sum += sequence[j++];
while(sum > k && i < j){
sum -= sequence[i++];
}
if(sum == k){
if(j - i < minLength){
minLength = j - i;
start = i;
end = j - 1;
}
}
}
answer = new int[]{start, end};
return answer;
}
}
class Solution {
public int[] solution(int[] sequence, int k) {
int N = sequence.length;
int left = 0, right = N;
int sum = 0;
for(int L = 0, R = 0; L < N; L++) {
while(R < N && sum < k) {
sum += sequence[R++];
}
if(sum == k) {
int range = R - L - 1;
if((right - left) > range) {
left = L;
right = R - 1;
}
}
sum -= sequence[L];
}
int[] answer = {left, right};
return answer;
}
}