반응형

1. 첫번째부터 롤러질

2. 어디까지 칠해졌는지 기록 <= checked

3. 칠할 section을 돌면서 checked보다 같거나 작은지 체크(칠해진거)

4. section이 칠해진 지점보다 크면 롤러횟수+1, 어디까지 칠해졌는지 기록.

5. 칠해진 지점이 전체 길이보다 같거나 크면 stop

class Solution {
    public int solution(int n, int m, int[] section) {
        int answer = 0;
        int checked = 0; //checked까지 칠해졌음
        
        
        for(int sec : section){
            if(checked >= sec){
                continue;
            }else{
                checked = sec + (m-1);
                answer += 1;
            }
            
            if(checked >= n) break;
        }
        
        return answer;
    }
}
반응형

'코딩 관련 > 코딩문제풀기' 카테고리의 다른 글

[프로그래머스] Lv1. 과일 장수  (0) 2024.11.16
[프로그래머스] Lv1. 소수 찾기  (0) 2024.11.16
[백준] 부분합  (0) 2024.11.14
[백준] 세 수 java  (0) 2024.11.14
[백준] 단지번호붙이기 java  (0) 2024.11.14
반응형

투 포인터라는 알고리즘을 배웠음!

핵심 원리는 다음과 같음

1. start pointer / end pointer

2. end pointer을 오른쪽으로 옮기면 합이 증가

3. start pointer을 오른쪽으로 옮기면 합이 감소

4. pointer 이동한 뒤 목표합보다 작으면 -> end pointer를 오른쪽으로 옮긴다.

5. pointer 이동한 뒤 목표합보다 크면 -> start pointer를 오른쪽으로 옮긴다.

이제 여기서 문제마다

목표합과 같을때 무슨 액션을 할지 달라지는가 보다.

두번째 문제풀이

import java.util.*;

public class Problem1806 {
    //부분합
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numsCount = sc.nextInt();
        int targetSum = sc.nextInt();
        sc.nextLine();
        int[] nums = new int[numsCount];
        for(int i=0; i<numsCount; i++){
            nums[i] = sc.nextInt();
        }

        int end = 0;
        int start = 0;
        int sum = 0;
        int minLen = numsCount+1;
        //end 포인터를 오른쪽으로 옮기면 합이 증가
        //start 포인터를 오른쪽으로 옮기면 합이 감소
    
        while(end < numsCount){ //end 포인터가 배열 마지막부분까지 가도록
            if(sum < targetSum){ //합이 목표합보다 작은 경우 : end 포인터를 오른쪽으로 옮긴다.
                sum += nums[end++];
            }
            while(sum >= targetSum){//합이 목표합보다 크거나 같은 경우 : start 포인터를 오른쪽으로 옮긴다.
                sum -= nums[start++];
                minLen = Math.min(minLen, end-start+1);
            }
        }
        
        if(minLen == numsCount + 1){
            System.out.println(0);
        }else{
            System.out.println(minLen);
        }
    }
    
}

 

첫번째 문제풀이

import java.util.*;

public class Problem1806 {
    //부분합
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numsCount = sc.nextInt();
        int targetSum = sc.nextInt();
        sc.nextLine();
        int[] nums = new int[numsCount];
        for(int i=0; i<numsCount; i++){
            nums[i] = sc.nextInt();
        }

        int start = 0;
        int sum = 0;
        int minLen = numsCount+1;
        for(int end=0; end<numsCount; end++){
            sum += nums[end]; //end에 있는 수 더하기

            while(sum >= targetSum){//목표합보다 같거나 큰 경우 길이를 기록, start을 오른쪽으로 땡김
                minLen = Math.min(end-start+1,minLen);
                sum -= nums[start++];      
            } 

        }
        minLen = minLen == numsCount+1 ? 0 : minLen;
        System.out.println(minLen);
    }
    
}

 

아래코드는 다음과 같이 바꿀 수 있음

start += 1; 
sum -= nums[start-1];

=> sum -= nums[start++];

 

반응형

'코딩 관련 > 코딩문제풀기' 카테고리의 다른 글

[프로그래머스] Lv1. 소수 찾기  (0) 2024.11.16
[프로그래머스] Lv1. 덧칠하기  (0) 2024.11.15
[백준] 세 수 java  (0) 2024.11.14
[백준] 단지번호붙이기 java  (0) 2024.11.14
[백준] 바이러스 java  (0) 2024.11.12
반응형

boxed를 해주는 이유

1. Comparator는 객체를 비교하는 인터페이스이다.
2. Instream은 기본 데이터 타입인 int 를 다루는 스트림이므로 Comparator를 사용할 수 없다.
3. 따라서 boxed()를 사용하여 IntStream을 Stream<Integer>로 변환한다.

import java.util.*;

public class Problem10817 {
    // 세 수
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] nums = sc.nextLine().split(" ");
        Optional<Integer> num = Arrays.stream(nums)
                                .mapToInt(Integer::parseInt)
                                .boxed()
                                .sorted((a,b) -> b-a)
                                .skip(1)
                                .findFirst();

        System.out.println(num.get());
    }
}
반응형

'코딩 관련 > 코딩문제풀기' 카테고리의 다른 글

[프로그래머스] Lv1. 덧칠하기  (0) 2024.11.15
[백준] 부분합  (0) 2024.11.14
[백준] 단지번호붙이기 java  (0) 2024.11.14
[백준] 바이러스 java  (0) 2024.11.12
[백준] 미로탐색 java  (0) 2024.11.07
반응형

오랜만에 stream sorted사용

사전순 정렬시

Comparator.naturalOrder() 혹은

String::compareTo 사용하면 된다고 함

import java.util.*;

public class Problem1181 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int cnt = Integer.parseInt(sc.nextLine());
        String[] words = new String[cnt];
        for(int i=0; i<cnt; i++){
            words[i] = sc.nextLine();
        }

        String[] newWords = Arrays.stream(words)
                        .distinct()
                        .sorted(Comparator.comparingInt(String::length)
                        .thenComparing(Comparator.naturalOrder()))
                        .toArray(String[]::new);

        for(String w : newWords){
            System.out.println(w);
        }
    }
    
}

 

 

반응형
반응형

문제 제대로 안 읽고 오름차순인거 캐치 못하고 계속 삽질..

나는 왜그럴까.. 

import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Scanner;

public class Main {
    static boolean[][] isChecked; //체크여부
    static int[][] map;           //지도
    static int mapSize;           //지도의 크기
    static Deque<int[]> queue = new ArrayDeque<>();   //방문할 좌표
    static int[] xmove = new int[]{-1, 1, 0, 0};           //상하좌우
    static int[] ymove = new int[]{0, 0, -1, 1};           //상하좌우
    static int townCnt = 0;
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        mapSize = Integer.parseInt(sc.nextLine());
        map = new int[mapSize][mapSize];
        isChecked = new boolean[mapSize][mapSize];

        //map 저장
        for(int i=0; i<mapSize; i++){
            String row = sc.nextLine();
            for(int j=0; j<row.length(); j++){
                map[i][j] = row.charAt(j) - '0';
            }
        }

        for(int i=0; i<mapSize; i++){
            for(int j=0; j<mapSize; j++){
                if(!isChecked[i][j] && map[i][j] == 1){ //방문체크 안되어있는 1값인 경우 시작
                    townCnt += 1; //단지 카운트
                    bfs(i, j);
                }
            }
        }
        System.out.println(townCnt);
        Collections.sort(townSizes);
        for(Integer cnt : townSizes){
            System.out.println(cnt);
        }
    }
    static List<Integer> townSizes = new ArrayList<>();
    public static void bfs(int x, int y){
        int townSize = 1;
        queue.add(new int[]{x, y});
        isChecked[x][y] = true;
        while(!queue.isEmpty()){
            int[] position = queue.poll();
            for(int i=0; i<4; i++){
                int newx = position[0] + xmove[i];
                int newy = position[1] + ymove[i];
                if(newx >= 0 && newy >= 0 && newx < mapSize && newy < mapSize
                    && map[newx][newy] == 1
                    && !isChecked[newx][newy]
                ){
                    queue.add(new int[]{newx, newy});
                    isChecked[newx][newy] = true;
                    townSize += 1;
                }
            }
        }

        townSizes.add(townSize);    
        
    }
}
반응형

'코딩 관련 > 코딩문제풀기' 카테고리의 다른 글

[백준] 부분합  (0) 2024.11.14
[백준] 세 수 java  (0) 2024.11.14
[백준] 바이러스 java  (0) 2024.11.12
[백준] 미로탐색 java  (0) 2024.11.07
[백준] 보석 도둑 java  (0) 2024.10.30
반응형

DFS 사용

import java.io.File;
import java.util.Scanner;

public class Problem2606 {
    static int[][] map; //연결망
    static boolean[] isChecked; //체크여부
    static int computerCnt; //컴퓨터 개수
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        computerCnt = Integer.parseInt(sc.nextLine());
        int lineCnt = Integer.parseInt(sc.nextLine());
        isChecked = new boolean[computerCnt+1];
        map = new int[computerCnt+1][computerCnt+1];

        //map에 연결여부 넣기
        for(int i=1; i<=lineCnt; i++){
            String[] line = sc.nextLine().split(" ");
            int a = Integer.parseInt(line[0]);
            int b = Integer.parseInt(line[1]);
            map[a][b] = map[b][a] = 1;
        }

        dfs(1);
        System.out.println(virusCnt);
    }

    static int virusCnt = 0;
    public static void dfs(int start){
        isChecked[start] = true;
        for(int i=1; i<=computerCnt; i++){
            if(map[start][i] == 1 && !isChecked[i]){ //방문한 적 없고 연결1이면
                virusCnt+=1;
                dfs(i);
            }
        }
    }
}
반응형

'코딩 관련 > 코딩문제풀기' 카테고리의 다른 글

[백준] 세 수 java  (0) 2024.11.14
[백준] 단지번호붙이기 java  (0) 2024.11.14
[백준] 미로탐색 java  (0) 2024.11.07
[백준] 보석 도둑 java  (0) 2024.10.30
[백준] ATM  (0) 2024.10.29
반응형

(1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하기

 

필요한 변수

n : 행사이즈
m : 열사이즈
xmove : x좌표 상하좌우 이동값
ymove : y좌표 상하좌우 이동값
queue : bfs 탐색시 필요한 탐색예정 좌표 담을 큐
isChecked : 방문여부
cnt : 1,1로부터 해당칸의 거리

 

로직

1. 지도를 2차원 배열에 저장
2. 현재좌표 0,0 부터 큐에 담기
3. 현재좌표를 기준으로 상하좌우가 이동조건에 맞는지 탐색
 - 이동조건 : 값이 1 && check가 false && 배열범위 내
4. 조건에 부합하는 경우 큐에 넣기, check를 false로 기록, 거리(cnt) 기록

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static int n,m;
    public static int[][] map;
    public static int[] xmove = {-1,1,0,0}; //상 하 좌 우
    public static int[] ymove = {0,0,-1,1};
    public static Deque<int[]> queue = new ArrayDeque<>();
    public static boolean[][] isChecked;
    public static int[][] cnt;
    
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] nm = br.readLine().split(" ");
        n = Integer.parseInt(nm[0]); //행 개수
        m = Integer.parseInt(nm[1]); //열 개수
        map= new int[n][m]; //지도
        isChecked = new boolean[n][m]; //방문 여부
        cnt = new int[n][m];

        //지도 저장
        for(int i=0; i<n; i++){
            String row = br.readLine();
            for(int j=0; j<m; j++){
                map[i][j] = row.charAt(j) - '0';
            }
        }
        bfs();
        System.out.println(cnt[n-1][m-1]);

    }

    public static void bfs(){
        cnt[0][0] = 1;
        queue.offer(new int[]{0,0});

        while(!queue.isEmpty()){
            int[] position = queue.poll();
            int x = position[0];
            int y = position[1];

            //2. 상화좌우의 이동 가능 좌표 탐색
            for(int i=0; i<4 ;i++){
                int newx = x + xmove[i];
                int newy = y + ymove[i];

                //값이 1이어야 하며, check 안된 곳, 범위를 벗어나지 않아야 함.
                if(newx >= 0 && newy >= 0 && newx < n && newy < m
                && map[newx][newy] == 1
                && !isChecked[newx][newy]){
                    queue.offer(new int[]{newx,newy}); //3. 큐에 넣기
                    isChecked[newx][newy] = true; //방문여부 체크
                    cnt[newx][newy] = cnt[x][y] + 1; //다음 위치 cnt 기록
                }
            }

        }
    }

}
반응형

'코딩 관련 > 코딩문제풀기' 카테고리의 다른 글

[백준] 단지번호붙이기 java  (0) 2024.11.14
[백준] 바이러스 java  (0) 2024.11.12
[백준] 보석 도둑 java  (0) 2024.10.30
[백준] ATM  (0) 2024.10.29
[백준] 설탕 배달  (0) 2024.10.29
반응형

그래프 사용이유

1. 여러 객체간의 관계를 논리적이고 시각적으로 표현할 수 있음 
└ 두 개체간의 경로, 연결여부 등을 표시함
2. 경로 탐색이나 최단 경로 계산을 할 수 있음

 

StringTokenizer : 문자열을 구분자(delimiter)로 분리하여 토큰(token)으로 나누는 클래스. 구분자를 지정하지 않으면 기본적으로 공백을 구분자로 사용

hasMoreTokens(): 다음 토큰이 있는지 확인하여 boolean을 반환합니다.
nextToken(): 다음 토큰을 반환하고, 토큰이 없으면 예외를 발생시킵니다.
countTokens(): 남아 있는 토큰의 개수를 반환합니다.

BufferedReader : 문자 데이터를 버퍼에 담아 한 번에 읽고 처리

InputStreamReader : System.in과 같은 콘솔입력 등을 바이트 스트림을 문자 스트림으로 변환

 

BufferedReader는 단순히 데이터를 읽어와 한 줄 단위로 문자열로 반환하는 반면, Scanner는 입력을 토큰화하고 데이터 타입에 맞게 변환

StringBuilder 사용해서 한번 출력하는게 

매번 System.out.print 찍는것보다 미세하게 빠름

 

배열 생성시 정점 개수로 하느냐, 간선 개수로 하느냐 때문에 메모리 초과 떴었음

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static int n, m, v; //n=정점의 개수, m=간선의 개수, v=시작 정점 번호
    public static int[][] arr;
    public static boolean[] isVisited;
    public static Deque<Integer> queue = new ArrayDeque<>();
    public static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer strtk = new StringTokenizer(br.readLine());
        n = Integer.parseInt(strtk.nextToken());
        m = Integer.parseInt(strtk.nextToken());
        v = Integer.parseInt(strtk.nextToken());

        arr = new int[n+1][n+1]; //간선 배열
        isVisited = new boolean[n+1]; //정점 방문 여부 배열


        for(int i=0; i<m ; i++){ //간선 읽어서 배열에 저장
            strtk = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(strtk.nextToken());
            int b = Integer.parseInt(strtk.nextToken());
            arr[a][b] = arr[b][a] = 1; //선이 연결된 경우 1
        }

        dfs(v);
        Arrays.fill(isVisited,false);
        System.out.print("\n");
        bfs(v);

    }
    //depth first search
    public static void dfs(int start){
        isVisited[start] = true;
        System.out.print(start + " ");
        for(int i=1; i<= n; i++){
            //간선이 연결되어 있고 방문한적 없는 정점인 경우
            if(arr[start][i] == 1 && !isVisited[i]){
                dfs(i);
            }
        }
    }

    //breadth first search
    public static void bfs(int start){
        isVisited[start] = true;
        queue.offer(start);
        while(!queue.isEmpty()){
            int s = queue.poll();
            System.out.print(s + " ");
            for(int i=1; i<=n; i++){
                if(arr[s][i] == 1 && !isVisited[i]){
                    queue.offer(i);
                    isVisited[i] = true;
                }
            }
        }
    }
}
반응형
반응형

처음 시도 

1. 보석의 무게와 가격을 이중배열에 담는다.
2. 보석 2중배열을 가격을 기준으로 내림차순 정렬
3. 가방 무게 배열을 오름차순 정렬
4. 가방 배열과 보석 배열 이중 for문, 조건 : 보석무게 <= 가방무게인 경우 가격을 +, 값은 -1 세팅
=> 이중 for문으로 모든 가방마다 보석배열을 쭉 돌게 됨

결과 : 시간초과

 

2차 시도

1. 보석의 무게와 가격을 이중배열에 담는다.
2. 보석 2중배열을 가격을 기준으로 내림차순 정렬 무게 기준 오름차순 정렬
3. 가방 무게 배열을 오름차순 정렬
4. 가방 배열 순회 for, 보석 배열 순회 while, 조건 : 보석무게 <= 가방무게인 경우 
가격을 우선수위 큐에 담고 보석배열 인덱스 증가시킴. 보석 배열은 한 번만 순회함.
가방에 담을 수 있는 보석 중 가장 비싼 가격을 뽑아서 +.

결과 : 시간초과

 

3차 시도

1. 보석의 무게와 가격을 담는 이중배열에 담는다.  객체를 만든다.
2. 보석 객체 배열 무게 기준 오름차순 정렬
3. 가방 무게 배열을 오름차순 정렬
4. 가방 배열 순회 for, 보석 배열 순회 while, 조건 : 보석무게 <= 가방무게인 경우 
가격을 우선수위 큐에 담고 보석배열 인덱스 증가시킴. 보석 배열은 한 번만 순회함.

가방에 담을 수 있는 보석 중 가장 비싼 가격을 뽑아서 +.

결과 : 통과

 

* 이중배열과 객체배열을 사용하는 것의 시간 차이가 있는 것으로 보임

* 우선순위 큐 최대 힙

PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());

 

* 배열 정렬에 Comparator 사용

Arrays.sort(jewels,Comparator.comparingInt((int[] a)->a[0]));
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        //목적 최대한 비싼 보석 넣기
        Scanner sc = new Scanner(System.in);
        int jewelCnt = sc.nextInt();
        int bagCnt = sc.nextInt();

        //보석 무게와 가격 정보
        Jewelry[] jewels = new Jewelry[jewelCnt];
        for(int i=0; i<jewelCnt; i++){
            Jewelry temp = new Jewelry(sc.nextInt(), sc.nextInt());
            jewels[i] = temp;
        }

        //보석 무게 오름차순
        Arrays.sort(jewels, Comparator.comparingInt(j -> j.mass));

        //가방 정보
        int[] bagInfo = new int[bagCnt];
        for(int i=0; i<bagCnt; i++){
            bagInfo[i] = sc.nextInt();
        }
        //가방 무게 적은 순 정렬
        Arrays.sort(bagInfo);        
        
        long sum = 0;
        int jewelIndex = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
        for (int bag : bagInfo) {
            // 현재 가방 무게에 맞는 모든 보석을 추가
            while (jewelIndex < jewels.length && jewels[jewelIndex].mass <= bag) {
                pq.offer(jewels[jewelIndex].price);
                jewelIndex++;
            }
            // 가장 비싼 보석 선택
            if (!pq.isEmpty()) {
                sum += pq.poll(); // 선택된 보석은 다른 가방에서 사용되지 않음
            }
        }
        
        System.out.println(sum);
    } 
}

class Jewelry {
    int mass; // 무게
    int price; // 가격
 
    Jewelry(int mass, int price) {
        this.mass = mass;
        this.price = price;
    }
}
반응형

'코딩 관련 > 코딩문제풀기' 카테고리의 다른 글

[백준] 바이러스 java  (0) 2024.11.12
[백준] 미로탐색 java  (0) 2024.11.07
[백준] ATM  (0) 2024.10.29
[백준] 설탕 배달  (0) 2024.10.29
[프로그래머스] Lv1. 실패율  (0) 2024.10.28
반응형

11399번

제일 앞에서는 사람이 걸리는 시간은 뒤의 사람 수만큼 곱해지므로 오름차순으로 세우면 됨

import java.util.*;

public class Problem11399 {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int cnt = sc.nextInt(); //사람수
        sc.nextLine();
        String[] temptimes = sc.nextLine().split(" ");
        int[] times = Arrays.stream(temptimes)
                    .mapToInt(Integer::parseInt)
                    .toArray();
        Arrays.sort(times); //오름차순 정렬
        
        int timeTotal = 0;
        for(int time : times){
            timeTotal += time * cnt;
            cnt -= 1;
        }
        System.out.println(timeTotal);
    }
}
반응형

+ Recent posts