<사전 생각>

문자열을 합치는 과정이 빈번히 일어나기 때문에 String += "op"식의 방법 보다는 StringBuilder.append()를 사용하는 것이 효과적이라는 사실을 생각해야 했고 

제일 중요한 중간을 터치하는 손가락을 어떻게 판별 할 것인가를 고민해야 했다.

단순하게 배열을 사용하여 x,y 좌표를 두고 계산 할 생각을 하였다.

 

<최종 코드>

class Solution {
    //시간 복잡도 O(n), 공간 복잡도 O(1)
    public String whichIsNeer(int left[], int right[], int targetY, String samePoint){
        int pos[] = {2,targetY};
        int leftGap = Math.abs(pos[0]-left[0])+Math.abs(pos[1]-left[1]);
        int rightGap = Math.abs(pos[0]-right[0])+Math.abs(pos[1]-right[1]);
        if(rightGap<leftGap)
            return "R";
        else if(leftGap<rightGap)
            return "L";
        else return samePoint;
    }
    public String solution(int[] numbers, String hand) {
        String samePoint = hand.equals("right")?"R":"L";
        // 문자열길이를 수정할 때는 StringBuilder가 가장 효율적임
        StringBuilder answer = new StringBuilder("");
        // x,y좌표 저장
        //  1-1   2-1   3-1
        //  1-2   2-2   3-2
        //  1-3   2-3   3-3
        //  1-4   2-4   3-4
        int leftLocation[] = {1,4}; // 위에서 부터 1 2 3 4는 *
        int rightLocation[] = {3,4}; // 위에서 부터 1 2 3 4는 #

        for(int i=0;i<numbers.length;i++){
            if(numbers[i]==1||numbers[i]==4||numbers[i]==7) {
                answer.append("L");
                leftLocation[0] = 1;
                leftLocation[1] = (numbers[i]+2)/3;
            }
            else if(numbers[i]==3||numbers[i]==6||numbers[i]==9) {
                answer.append("R");
                rightLocation[0] = 3;
                rightLocation[1] = numbers[i]/3;
            }
            // 핵심
            else{
                int posY = 4;
                if(numbers[i]!=0)
                    posY=(numbers[i]+1)/3;
                String tmp = whichIsNeer(leftLocation,rightLocation,posY,samePoint);
                if(tmp.equals("L")) {
                    leftLocation[0] = 2;
                    leftLocation[1] = posY;
                }
                else {
                    rightLocation[0] = 2;
                    rightLocation[1] = posY;
                }
                answer.append(tmp);
            }
        }
        return answer.toString();
    }
}

<더 생각해봐야 할 점>

좀 더 효율적으로 중앙을 터치할 손가락을 판별 할 방법은 없을까?

 

<링크>

https://school.programmers.co.kr/learn/courses/30/lessons/67256

모든 달의 일을 28일로 두고 계산한다고 가정하였기 때문에 정수로 바꾸어 크키를 비교하여 폐기여부를 결정하는 알고리즘을 짜서 해결하고자 하였다.

<사전 생각>

정수(Int) 의 범위는 -2^31 ~ 2^31-1 약 (-21억~+21억) 사이 이기 때문에 정수 범위를 초과하여 문제가 발생하는 경우는 없다고 생각하고 

"1971.11.01" 식의 문자열을 분리 하여야 하는데 split() 함수를 사용할 수 도 있겠지만 

해당 Built-in 함수는 시간소모가 크다는 걸 LeetCode 로 충분히 경험 하였기 때문에 가급적 subString() 함수로 해결하고자 하였다.  

 

<최종 코드>

import java.util.Vector;
// split() 함수를 안쓰는 이유는 시간적으로 소모가 크기 때문 가급적 substring()으로 해결
class Solution {
    // "1971.12.01" 형식의 날짜를 day 수로 변환하는 함수
    private int getParseIntDay(String date){
        int day = 0;
        day+=Integer.parseInt(date.substring(0,4))*28*12;
        day+=Integer.parseInt(date.substring(5,7))*28;
        day+=Integer.parseInt(date.substring(8,10));
        return day;
    }
    // 시간 복잡도 O(nm) 공간 복잡도 O(n+m);
    public int[] solution(String today, String[] terms, String[] privacies) {
        // 당신은 오늘 날짜로 파기해야 할 개인정보 번호들을 구하려 합니다.
        int[] answer = {};
        int dDay = getParseIntDay(today); // 마감기한 구하기
        int[] privaciesInt = new int[privacies.length]; // 저장할 제품기간의 공간
        Vector<Integer> v = new Vector<Integer>(); // 폐기해야 할 데이터의 번호들을 효과적을 저장할 자료구조
        // 제품의 유통기한을 day 수로 변환하여 저장
        for(int i=0;i<privaciesInt.length;i++)
            privaciesInt[i] = getParseIntDay(privacies[i].substring(0,10));
        // (브루트 포스) 모든 경우 검사
        for(int i=0;i< privacies.length;i++){
            for(int j=0;j< terms.length;j++) {
                // 만약 제품의 약관 종류가 같다면 해당 약관의 day만큼 추가
                if (privacies[i].charAt(privacies[i].length()-1)==
                        terms[j].charAt(0)){
                    String mouth = terms[j].substring(2,terms[j].length());
                    privaciesInt[i]+=Integer.parseInt(mouth)*28;
                }
            }
        }
        // 폐기해야할 제품 번호 저장
        for(int i=0;i<privaciesInt.length;i++){
            if(dDay>=privaciesInt[i])
                v.add(i+1);
        }

        int ans[] = new int[v.size()];
        for(int i=0;i<ans.length;i++)
            ans[i] = v.get(i);
        answer = ans;

        return answer;
    }
}

<더 생각해봐야 할 점>

다른 분들의 답안을 보면 나와 같이 숫자로 변환하여 처리하지 않고 날짜 형식으로 format 처리 하여 푼 걸 볼 수 있었는데

그런 방향의 풀이도 고안해 보아야 할 것 같다.

 

<링크>

https://school.programmers.co.kr/learn/courses/30/lessons/150370

+ Recent posts