[프로그래머스] 코딩테스트 입문 Day 13 with Java

2025. 1. 6. 23:28코딩테스트 리뷰(프로그래머스)/코딩 기초 트레이닝 with Java

1. 컨트롤 제트

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int solution(String s) {
        String[] list = s.split(" ");
        int answer = 0;
        for( int i = 0; i < list.length; i++ ) {
            if( list[i].equals("Z") ) {
                answer -= Integer.parseInt(list[i-1]);
            } else 
                answer += Integer.parseInt(list[i]);
        }
        return answer;
    }
}

 

 

 

2. 배열 원소의 길이

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int[] solution(String[] strlist) {
        int[] answer = new int[strlist.length];
        for( int i = 0; i < strlist.length; i++) {
            answer[i] = strlist[i].length();
        }
        return answer;
    }
}

 

 

 

3. 중복된 문자 제거

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

import java.util.*;
import java.util.stream.Collectors;
class Solution {
    public String solution(String my_string) {
        
        return Arrays.stream(my_string.split("")).distinct().collect(Collectors.joining());
    }
}

 

기타 참고

이번 프로그래머스의 문제에서는 stream.toList 메소드가 동작이 안되었다.

해결방법을 찾아보니 collect(Collectors.toList()) 을 사용하면 list 화가 된다.

그리고 해당 문제는 String 으로 리턴을 하는 것이니

Collectors.joining 을 사용하면 String으로 한번에 묶인다.

 

 

4. 삼각형의 완성조건 (1)

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

class Solution {
    public int solution(int[] sides) {
        int max = Integer.MIN_VALUE;
        int answer = 0;
        for( int i = 0; i < sides.length; i++) {
            max = Math.max(max, sides[i]);
        }
        for( int i = 0; i < sides.length; i++) {
            answer += sides[i];
        }
        answer -= max;
        
        return answer > max ? 1 : 2;
    }
}

 

다른 풀이

다른 사람 풀이를 살펴보니 Arrays.sort()을 사용해서 풀은 경우가 있었다.

Arrays.sort() 같은 경우는 dual pivot quick sort을 사용한다.

이의 시간 복잡도는 O(nlogn) 이다. 위에 코드 같은 경우는 O(n)이므로 시간 복잡도는 약간 더 좋다고 말할 수 있다.

 

참고

 

퀵 정렬 - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 퀵 정렬(Quicksort)은 찰스 앤터니 리처드 호어가 개발한 범용 정렬 알고리즘이다. 다른 원소와의 비교만으로 정렬을 수행하는 비교 정렬에 속한다. 퀵 정렬은 n개

ko.wikipedia.org