반응형

 

 

 

안녕하세요

Henry's Algorithm의 Henry입니다.

 

오늘은 제가 프로그래머스 

Level 2의 프린터 문제를 풀어보았습니다.

 

첫 시도는 잘 안풀렸는데,

다음날 다시 풀어보니까, 생각이 잘 정리되서 잘 풀렸네요!ㅎㅎ

 

 

문제는 푸는 요령:

저는 Queue 자료구조를 사용해서 풀었습니다.

priorities와 index 정보를 가지고 있는 배열 각각 1개씩 만들고,

while 문을 통해 priorities가 모두 pop 되기 전까지 우선순위를 비교하는 과정을 반복했습니다.

 

- java.util.Collections을 import해서 List의 최대, 최소를 구할 수 있어, 해당 라이브러리를 사용했습니다.

 

아래는 제가 푼 코드입니다.

import java.util.Queue;
import java.util.LinkedList;
import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        
        Queue<Integer> indexs = new LinkedList<>();
        Queue<Integer> priors = new LinkedList<>();
        
        for(int i = 0; i< priorities.length; i++){
            priors.add(priorities[i]);
            indexs.add(i);
        }
        
        while(!priors.isEmpty()){
            int front = priors.poll();
            int frontIdx = indexs.poll();
            
            int max = priors.isEmpty() ? -1 : Collections.max(priors);
            
            if(max == -1){
                return answer + 1;
            }
            
            if(front >= max){
                answer += 1;
                if(frontIdx == location){
                    return answer;
                }
                continue;
            }
            
            priors.add(front);
            indexs.add(frontIdx);
        }
        
        return answer;
    }
}

 

 

오늘도 즐거운 코딩되세요~!ㅎㅎ

반응형
반응형

 

 

 

안녕하세요

Henry's Alogirthm의 Henry 입니다.

 

오늘은 프로그래머스의 기능개발 문제를 풀어보았습니다.

 

문제 푸는 요령:

순서가 중요한 문제여서

배열의 인덱스를 중점적으로 활용해서 푸는 문제입니다.

"순서 -> 인덱스 활용"

 

for문으로 순차적으로 접근해주면서 비교 연산자를 통해 풀어주시면 됩니다.

 

아래는 저의 코드입니다.

 

import java.util.Arrays;

class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        int[] dayOfend = new int[100];
        int day = 0; // 오늘 /  1 -> 하루 뒤
        
        for(int i=0; i<progresses.length; i++){
            while(progresses[i] + day*speeds[i] < 100){
                day ++;
            }
            
            dayOfend[day] ++;
        }
        
        return Arrays.stream(dayOfend).filter(i -> i != 0).toArray();
    }
}

 

 

그럼 오늘도 즐거운 코딩되세요~!ㅎㅎ

반응형
반응형

 

안녕하세요~!

 

Henry's Algorithm의 헨리입니다.

 

오늘은 자바로 문제를 풀어보았습니다.

 

문제 푸는 요령:

두개의 배열중에 하나만 딱 다를때,

정렬을 한 후에 동등비교를 통해서 문제를 풀 수 있게 됩니다.

 

아래 제가 푼 코드를 올려놓겠습니다.

 

다들 열공하시기 바랍니다.

import java.util.Arrays;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        
        Arrays.sort(participant);
        Arrays.sort(completion);
        
        for(int i=0; i<completion.length; i++){
            if(!completion[i].equals(participant[i])){
                return participant[i];
            }
        }
        
        answer = participant[participant.length - 1];
        
        return answer;
    }
}
반응형
반응형

문제 설명

위와 같은 삼각형의 꼭대기에서 바닥까지 이어지는 경로 중, 거쳐간 숫자의 합이 가장 큰 경우를 찾아보려고 합니다. 아래 칸으로 이동할 때는 대각선 방향으로 한 칸 오른쪽 또는 왼쪽으로만 이동 가능합니다. 예를 들어 3에서는 그 아래칸의 8 또는 1로만 이동이 가능합니다.

삼각형의 정보가 담긴 배열 triangle이 매개변수로 주어질 때, 거쳐간 숫자의 최댓값을 return 하도록 solution 함수를 완성하세요.

제한사항

  • 삼각형의 높이는 1 이상 500 이하입니다.
  • 삼각형을 이루고 있는 숫자는 0 이상 9,999 이하의 정수입니다.

입출력 예

triangleresult

[[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]] 30

출처

 

Sweden

International Olympiad in Informatics – Statistics Contact information Participation in IOI (based on database records) First participation: 1990Years participated: 31Contestants participated: 82 Perfomance in IOI Gold medals: 13Silver medals: 30Bronze m

stats.ioinformatics.org

 

 

 

프로그래머스의 LEVEL 3에 있는 정수 삼각형 문제이다.

문제 설명을 보면 Dynamic Programming 개념을 통해서 풀라고 나와있다.

 

나는 동적 프로그래밍이 처음에는 재귀 호출을 통해서 푸는 방식이라고 생각했는데,

이 문제를 보면서 다시 알게 된 것은

 

재귀호출도 그렇고 이 정수 삼각형 문제도 그렇고

"처음부터 하나씩 쌓아나가는 개념" 이라는 것을 깨달았다.

 

내가 푼 방식은 for문을 2번 돌리면서 진행하는데,

생각한거와는 다르게 채점 시 Timeout 에러가 발생하지 않았고,

 

문제에 따라서는 모든 정수에 한번씩은 다 접근해야하는 경우에 이렇게 Dynamic Programming을 통해 풀 수 있는 거 같다.

 

아래는 내가 푼 코드이다.

 

def solution(triangle):

    for i in range(1,len(triangle)):
        for j in range(len(triangle[i])):
            if j == 0:
                triangle[i][j] += triangle[i-1][0]
            elif j == len(triangle[i])-1:
                triangle[i][j] += triangle[i-1][j-1]
            else:
                triangle[i][j] += max(triangle[i-1][j-1],triangle[i-1][j])
                
    return max(triangle[-1])

 

 

반응형
반응형

 

문제 설명

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.

컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.

제한사항

  • 컴퓨터의 개수 n은 1 이상 200 이하인 자연수입니다.
  • 각 컴퓨터는 0부터 n-1인 정수로 표현합니다.
  • i번 컴퓨터와 j번 컴퓨터가 연결되어 있으면 computers[i][j]를 1로 표현합니다.
  • computer[i][i]는 항상 1입니다.

입출력 예

ncomputersreturn

3 [[1, 1, 0], [1, 1, 0], [0, 0, 1]] 2
3 [[1, 1, 0], [1, 1, 1], [0, 1, 1]] 1

입출력 예 설명

예제 #1
아래와 같이 2개의 네트워크가 있습니다.

예제 #2
아래와 같이 1개의 네트워크가 있습니다.

 

 

 

프로그래머스의 LEVEL 3단계 문제이다.

풀이의 핵심은 DFS, BFS 함수를 정의하여 풀면 된다.

 

나는 DFS로 시작 컴퓨터 정하고, 깊이를 파고들어서 visit 리스트에 넣어주었다.

 

이후 다른 컴퓨터에 한번씩 접근했을 때

이전 컴퓨터를 통해 이미 visit 값에 포함되어 있다면 네트워크에 연결이 되어있는 컴퓨터라고 생각했다.

 

그래서 다른 컴퓨터에 접근할 때마다 visit가 늘어나게 되면 그 컴퓨터는 독립적인 네트워크라고 판단하여 문제를 풀었다.

 

 

풀이 코드

 

def solution(n, computers):
    
    # 네트워크 개수
    net_num = 0
    
    # 방문 컴퓨터 리스트
    visit = list()
    
    # 컴퓨터에 한번씩 접근하면서 깊이우선탐색 수행
    for i in range(len(computers)):
        net_num += dfs(computers,i,visit)
    
    return net_num


def dfs(computers, start_computer, visit):
    
    # 깊이 우선 탐색은 스택으로 구현한다.
    stack = list()
    
    # 신규 네트워크 여부
    is_connect = 0
    
    # 시작 컴퓨터
    stack.append(start_computer)
    
    while stack:
        node = stack.pop()
        if node not in visit:
            visit.append(node)
            stack.extend([i for i in range(len(computers[node])) if i != node and computers[node][i] != 0])
            is_connect = 1
            
    return is_connect
반응형
반응형

 

A non-empty array A consisting of N integers is given.

A peak is an array element which is larger than its neighbors. More precisely, it is an index P such that 0 < P < N − 1,  A[P − 1] < A[P] and A[P] > A[P + 1].

For example, the following array A:

A[0] = 1 A[1] = 2 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2

has exactly three peaks: 3, 5, 10.

We want to divide this array into blocks containing the same number of elements. More precisely, we want to choose a number K that will yield the following blocks:

  • A[0], A[1], ..., A[K − 1],
  • A[K], A[K + 1], ..., A[2K − 1],
    ...
  • A[N − K], A[N − K + 1], ..., A[N − 1].

What's more, every block should contain at least one peak. Notice that extreme elements of the blocks (for example A[K − 1] or A[K]) can also be peaks, but only if they have both neighbors (including one in an adjacent blocks).

The goal is to find the maximum number of blocks into which the array A can be divided.

Array A can be divided into blocks as follows:

  • one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks.
  • two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak.
  • three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block has a peak. Notice in particular that the first block (1, 2, 3, 4) has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] is in the adjacent block.

However, array A cannot be divided into four blocks, (1, 2, 3), (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do not contain a peak. Notice in particular that the (4, 3, 4) block contains two peaks: A[3] and A[5].

The maximum number of blocks that array A can be divided into is three.

Write a function:

class Solution { public int solution(int[] A); }

that, given a non-empty array A consisting of N integers, returns the maximum number of blocks into which A can be divided.

If A cannot be divided into some number of blocks, the function should return 0.

For example, given:

A[0] = 1 A[1] = 2 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2

the function should return 3, as explained above.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [0..1,000,000,000].

    Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

 

 

Peaks 문제는 봉우리를 최소 1개씩 포함하고 있는 Block의 개수를 구하는 문제이다.

 

최대 블록의 개수를 Return 해주면 되는데,

그 방법을 구체적으로 어떻게 짜야되는지 다양하게 시도하다가 

결국 답지를 보고 풀었다.ㅜㅜ!!

 

그래도 이 방법 잘 알아두어야겠다.

 

정답 코드

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(A):
    # write your code in Python 3.6
    
    peaks = []
    
    for i in range(1, len(A)-1):
        if A[i] > A[i-1] and A[i] > A[i+1]:
            peaks.append(i)
            
    for i in range(len(peaks),0,-1):
        if len(A) % i == 0:
            block_size = len(A)//i
            block = [False]*i
            block_cnt = 0
            for j in range(len(peaks)):
                idx = peaks[j] // block_size
                if block[idx] == False:
                    block[idx] = True
                    block_cnt += 1
            
            if block_cnt == i:
                return block_cnt
        
    return 0
        
    pass

 

반응형
반응형

하반기 취업이 시작되었다.

 

삼성, KT, CJ, 현대, 네이버 ,카카오 등

 

다양한 기업들이 슬슬 채용 공고를 내고 있다.

 

오늘은 교회에서 혼자 기도를 하며

 

스스로에게 물어보았다.

"내가 잘 할 수 있을까..?"

 

그래도 지금까지 잘 해온 것처럼 

취업준비생으로서 놓치지 말아야하는 것은 "감사하는 마음" 인것 같다.

 

지금까지 함께하신 하나님께서 앞으로도 함께 하시고,

나의 선한 목자되신다.

 

 

형광펜 칠한 것은 지원한 곳

 

 

 

이렇게 구글닥스에 정리하면서 준비하고 있다.

동시에 코딩테스트를 준비하고 있는데,

오늘은 지난 네이버 코딩테스트를 준비하며 제출한 부분에서

조금 애매했던 것인지, 한번 더 코테를 보라고 메일이 왔다.

 

 

이런 경우는 처음이여서 

내가 푼 코드가 딱 절반을 맞췄나보다 생각했다

 

재응시 답변을 드리고 나서, 바로 메일이 왔다.

 

 

이것도 조금 더 공부하고 지금까지 풀었던 것만 잘 복습한 후에

응시해야겠다.

 

 

 

지금 진행중인 것을 정리해보면

LG U+ 코딩테스트 대기

서울시설공단 필기 준비

카카오, 라인 코테 준비,

신한카드 코테 준비

 

 

 

나를 여기까지 인도하신 하나님을 찬양하고,

앞으로도 내 인생이 하나님의 선하신 손길 아래에 있을 것을 신뢰한다

 

 

 

- 취업의 시작점에서 짧은 글 -

반응형

+ Recent posts