seunghyun Note

[프로그래머스] -푸드 파이트 대회 with JAVA 본문

코딩테스트/백준

[프로그래머스] -푸드 파이트 대회 with JAVA

승숭슝현 2024. 1. 6. 21:41

링크 : https://school.programmers.co.kr/learn/courses/30/lessons/134240

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 풀이

1. 새롭게 저장할 배열의 길이 설정

2. 중간값 0으로 대입

3. 짝수일 경우는 -1

4. 양끝에서 중간까지 오면서 값을 대입한다.

import java.util.*;
class Solution {
   public String solution(int[] food) {
       int len=0;
       
       String answer = "";
       // 1. 길이 측정
       for(int i=1;i<food.length;i++){
           if(food[i] >1) {len += (food[i]%2 ==0) ? food[i] : food[i]-1; }
     
       }
       len +=1;
       // 새로운 배열 설정 + len 으로 할당
       int[] ans = new int[len];
       
       //중간값 0 대입
       ans[len/2] = 0;
      
       int cnt =1;
       int i=0;
       int j=len-1;

		//값 대입 시작
       while(cnt < food.length){
       //홀수일 경우 -1
           if(food[cnt]%2!=0) food[cnt]--;


		//양 끝에서 대입
           while(food[cnt] > 0){

               ans[i] = cnt;
               ans[j] =cnt;
               i++;
               j--;
               food[cnt]-=2;
           }
           cnt++;
       }
       
       
       for(int value : ans){
           System.out.print(value);
       }
       return answer = Arrays.toString(ans).replaceAll("[^0-9]","");
   }
}

다른 풀이

양 끝을 ' i + answer + i '로 해결하다니..

2중 For문을 통해 해결하되 크기는 'food[i]/2' 로 해결한다.

class Solution {
    public String solution(int[] food) {
        String answer = "0";

        for (int i = food.length - 1; i > 0; i--) {
            for (int j = 0; j < food[i] / 2; j++) {
                answer = i + answer + i; 
            }
        }

        return answer;
    }
}

 

728x90