프로그래머스

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

programmers.co.kr

 


풀이1

이렇게 푸니까 일단 통과는 하지만 테스트케이스 10번에서 시간이 오래 걸렸다.

  • 일단 k개를 제외하고 number.length() - k 개수만큼 숫자를 골라야 한다. => 반복문
  • 그리고 두번째 반복문에서는 각 회차에서 가장 큰 수(max)를 골라줘야 한다. 그런데 이 가장 큰 수를 고를 때 주의해야할 점이 있다. 바로 어디까지 중에서 (몇번째 인덱스까지) 가장 큰 수를 고를 것인가? 이다.
    • 1924, k=2라면 max를 고를 때 192 중에서 골라야한다. 왜냐면 두개의 수를 골라야 하기 때문에 (k=2이므로 2개 숫자 제거) 예를 들어, 1879라고 생각해보면 무작정 9를 고르면 그건 가장 큰 수가 되지 못하기 때문이다. 
    • 그래서 아래 그림과 같이 생각을 하면서 규칙을 찾아 k + i 인덱스까지 중에서 회차마다 가장 큰 수를 골라서 append해준다.

class Solution {
    public String solution(String number, int k) {
        StringBuffer sb = new StringBuffer();
        int index = 0;
        // 우리는 number.length() - k 개수를 숫자를 뽑을것이다
        for (int i = 0; i < number.length() - k; i++) {
            int max = 0;
            //큰수를 만들기 위해 뒤 숫자들 중 가장 큰수를 뽑아서 붙여줘야 한다
            for (int j = i; j <= i+k ; j++) {
                if (number.charAt(j) - '0' > max) {
                    max = number.charAt(i) - '0';
                    index = j + 1; // 다음 숫자부터 골라야하므로
                }
            }
            sb.append(max);
        }

        return sb.toString();
    }
}

반복문을 두번돌아 테스트10에서 속도가 매우 느리다는 것을 알 수 있다.


풀이2

다른분들의 풀이를 보니 스택을 이용해서 푼 풀이도 있었다. 

 

  • 스택에 들어있는 문자(stack.peek()) 가 현재 i번째 문자(charAt(i))보다 작으면 꺼낸다.
  • 문제는 k개의 숫자를 제거하는 것이므로, pop할때 k-- 로 k를 줄여준다. 
  • k개의 숫자가 pop되면(제거되면) 종료 후 스택에 있는 값을 꺼내준다. 

이런식으로 풀면 왼쪽에서부터 (앞에서부터) k개의 작은 수를 차례로 제거할 수 있다.

import java.util.Stack;
class Solution {
    public String solution(String number, int k) {
        char[] result = new char[number.length() - k];
        Stack<Character> stack = new Stack<>();

        for (int i=0; i<number.length(); i++) {
            char c = number.charAt(i);
            while (!stack.isEmpty() && stack.peek() < c && k-- > 0) {
                stack.pop();
            }
            stack.push(c);
        }
        for (int i=0; i<result.length; i++) {
            result[i] = stack.get(i);
        }
        return new String(result);
    }
}

- 분류 : DFS/BFS

 

- 문제 : https://www.acmicpc.net/problem/2606

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
class Computer {
    int num;//컴퓨터 번호
    boolean marked;//방문 여부
    LinkedList<Computer> adjacent;
 
    Computer(int num) {
        this.num = num;
        this.marked = false;
        this.adjacent = new LinkedList<>();
    }
}
 
class Graph {
    Computer[] computers;
    int count; //바이러스에 감염된 컴퓨터 수
 
    Graph(int size) {
        this.computers = new Computer[size];
        for (int i = 0; i < size; i++) {
            computers[i] = new Computer(i + 1);
        }
        count = 0;
    }
 
    void addEdge(int i1, int i2) {
        Computer c1 = computers[i1 - 1];
        Computer c2 = computers[i2 - 1];
        if (!c1.adjacent.contains(c2)) {
            c1.adjacent.add(c2);
        }
        if (!c2.adjacent.contains(c1)) {
            c2.adjacent.add(c1);
        }
    }
 
    void bfs() {
        Queue<Computer> queue = new LinkedList<>();
        Computer root = computers[0];
        root.marked = true;
        queue.add(root);
 
        while (!queue.isEmpty()) {
            Computer computer = queue.poll();
            for (Computer c : computer.adjacent) {
                if (c.marked == false) {
                    c.marked = true;
                    queue.add(c);
                }
            }
            visit(computer);
        }
    }
 
    void visit(Computer computer) {
        if (computer.num != 1) {
            count += 1;
        }
    }
}
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        sc.nextLine();
        int edges = sc.nextInt();
        sc.nextLine();
        Graph g = new Graph(size);
        for (int i = 0; i < edges; i++) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            g.addEdge(a, b);
            sc.nextLine();
        }
 
        g.bfs();
        System.out.print(g.count);
    }
}
 
cs

'알고리즘 > 백준' 카테고리의 다른 글

[백준1012/java] 유기농 배추  (0) 2023.05.12
[백준2606/java] 바이러스  (0) 2023.05.12
[백준/java] 1260번 - DFS와 BFS  (1) 2023.05.12
[백준/java] 18259번 - 큐2  (0) 2023.05.12
[백준/java] 2164번 - 카드2  (0) 2023.05.12

문제

 

코딩테스트 연습 - 2주차

[[100,90,98,88,65],[50,45,99,85,77],[47,88,95,80,67],[61,57,100,80,65],[24,90,94,75,65]] "FBABD" [[70,49,90],[68,50,38],[73,31,100]] "CFD"

programmers.co.kr

 

풀이

Map의 getOrDefault 메소드를 이용하여 같은 점수가 여러개 존재하는지 알아냈고, TreeMap을 이용하여 최고점과 최저점을 알아냈다. TreeMap은 key값이 자동정렬되기 때문에 key를 점수로 설정하면 firstKey()와 lastKey()로 최저점과 최고점을 알아낼 수 있었기 때문이다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.*;
 
class Solution {
    public String solution(int[][] scores) {
       StringBuilder answer = new StringBuilder();
 
        for(int i = 0; i<scores[0].length; i++) {
            int total = 0
            int person = scores[0].length;
            TreeMap<Integer, Integer> hm = new TreeMap<>();
 
            for(int j = 0; j<scores[i].length; j++) {
                hm.put(scores[j][i], hm.getOrDefault(scores[j][i], 0+ 1);
                total += scores[j][i];
            }
 
            if(scores[i][i] == hm.firstKey() && hm.get(hm.firstKey()) < 2) {
                total -= hm.firstKey();
                person -= 1;
            }
 
            if(scores[i][i] == hm.lastKey() && hm.get(hm.lastKey()) < 2) {
                total -= hm.lastKey();
                person -= 1;
            }
 
            answer.append(getGrade(total/person));
        }
 
        return answer.toString();
    }
 
    public String getGrade(double avg) {
        if(avg >= 90) {
            return "A";
        }
 
        else if(avg >= 80) {
            return "B";
        }
 
        else if(avg >= 70) {
            return "C";
        }
        else if(avg >= 50) {
            return "D";
        }
        else
            return "F";
    }
}
cs

 

 

 

아래는 좋아요를 가장 많이 받은 다른 사람의 풀이이다.

본인이 자기자신에게 매긴 점수를 제외하고 최고점과 최저점을 구했고, 구한 최저점과 최고점이 본인이 매긴 점수와 일치할 시에 제외하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
    public String solution(int[][] scores) {
        StringBuilder builder = new StringBuilder();
        for(int i=0; i<scores.length; i++) {
            int max = 0;
            int min = 101;
            int sum = 0;
            int divide = scores.length;
            for(int j=0; j<scores.length; j++) {
                int score = scores[j][i];
                if(i != j) {
                    if(score < min) {
                        min = score;
                    }
                    if(score > max) {
                        max = score;
                    }
                }
                sum += score;
            }
            if(scores[i][i] < min || scores[i][i] > max) {
                sum -= scores[i][i];
                divide--;
            }
            double score = (double) sum / divide;
            builder.append(score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 50 ? "D" : "F" );
        }
        return builder.toString();
    }
}
cs

'알고리즘 > 프로그래머스' 카테고리의 다른 글

[프로그래머스/java] 큰수 만들기  (0) 2023.07.14

- 문제 링크 : https://www.acmicpc.net/problem/1012

- 알고리즘 분류 : dfs/bfs

 

나는 DFS로 풀었다. 

 

  • input = 배추의 위치 좌표가 주어진 배열이 주어진다.
  • output = 필요한 배추흰지렁이의 개수
  • DFS 사용 ⇒ 한 방향으로 갈 수 있는 곳까지 계속 탐색하고, 막다른 곳에 들어가면 거기에서 다시 안으로 쭉 들어간다. 막다른 곳에 도달할 때마다 배추지렁이의 개수를 늘리면 될듯하다.

 

다 풀고나서 계속 25%에서 틀려서 디버깅해보니까 continue를 써야하는 시점에 break를 써놔서 상하좌우를 전부 체크하지 않고 반복문을 빠져나갔기 때문이었다;;; 너무 황당한 실수...

import java.util.*;

 class CabbageField {
    int count; //배추 개수
    int cabbageMap[][]; //배추 위치 좌표
    boolean visited[][]; 
    int width;
    int height;
    int result;
    
    private int dx[] = {1,-1,0,0};
    private int dy[] = {0,0,1,-1};
   
    
    public CabbageField(int w, int h, int c) {
        this.width = w;
        this.height = h;
        this.count = c;
        this.cabbageMap = new int[w][h];
        this.visited = new boolean[w][h];
    }   
 
    
    public void dfs(int x, int y) {
        this.visited[x][y] = true;
        checkAdjacent(x,y);
    }
    
    private void checkAdjacent(int x, int y) {
        //상하좌우 4군데 체크
        for(int i = 0; i<4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            
            if(nx >= width || nx < 0 || ny >= height || ny < 0) {
                continue;
            }
            
            //재귀
            if(visited[nx][ny] == false && cabbageMap[nx][ny] == 1) {
                dfs(nx, ny);
            }
        }
        
    }
}




public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int total = sc.nextInt(); // case 개수
        CabbageField[] cabbageFields = new CabbageField[total];
        for(int i = 0; i<total; i++) {
            cabbageFields[i] = new CabbageField(sc.nextInt(), sc.nextInt(), sc.nextInt());
            
            //배추 좌표 입력
            for(int j = 0; j<cabbageFields[i].count; j++) {
                int x = sc.nextInt();
                int y = sc.nextInt();
                cabbageFields[i].cabbageMap[x][y] = 1;
            }
            
            for(int w = 0; w<cabbageFields[i].width; w++) {
                for(int h = 0; h<cabbageFields[i].height; h++) {
                    if(cabbageFields[i].cabbageMap[w][h] == 1 
                        && cabbageFields[i].visited[w][h] == false) {
                            cabbageFields[i].dfs(w,h);
                            cabbageFields[i].result++;
                        }
                }
            }
            
           
            System.out.println(cabbageFields[i].result);
            
        }
       
    }
}

 

추가적으로 찾아본 반례를 첨부하면 아래와 같다.

 

<배추밭 모양>

0000

0101

0111

1
4 3 5
1 1
3 1
1 2
2 2
3 2

answer : 1

'알고리즘 > 백준' 카테고리의 다른 글

[백준/java] 2606번 - 바이러스  (0) 2023.05.12
[백준2606/java] 바이러스  (0) 2023.05.12
[백준/java] 1260번 - DFS와 BFS  (1) 2023.05.12
[백준/java] 18259번 - 큐2  (0) 2023.05.12
[백준/java] 2164번 - 카드2  (0) 2023.05.12

- 알고리즘 분류 : DFS/BFS

 

나는 BFS를 이용해서 풀었다.

 

  • 1번 컴퓨터가 바이러스에 걸렸을 때 감염된 컴퓨터 수를 구하라.
  • DFS, BFS 둘다 사용 가능하지만, 일단 인접한 컴퓨터를 기준으로 먼저 탐색할 것이기 때문에 나는 BFS를 이용해서 풀었다.
  • 1번 컴퓨터(root)를 시작으로 인접한 컴퓨터들부터 순차적으로 방문한다. 방문한 컴퓨터들은 연결되어있다는 뜻이므로 “감염된 컴퓨터의 수 = 방문한 컴퓨터의 수”가 된다.

 

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Computer {
    int num;//컴퓨터 번호
    boolean marked;//방문 여부
    LinkedList<Computer> adjacent; // 인접한 컴퓨터들

    Computer(int num) {
        this.num = num;
        this.marked = false;
        this.adjacent = new LinkedList<>();
    }
}

class Graph {
    Computer[] computers;
    int count; //바이러스에 감염된 컴퓨터 수

    Graph(int size) {
        this.computers = new Computer[size];
				// 컴퓨터 번호 매기기 
        for (int i = 0; i < size; i++) {
            computers[i] = new Computer(i + 1);
        }
        count = 0;
    }

    void addEdge(int i1, int i2) {
        Computer c1 = computers[i1 - 1];
        Computer c2 = computers[i2 - 1];
        if (!c1.adjacent.contains(c2)) {
            c1.adjacent.add(c2);
        }
        if (!c2.adjacent.contains(c1)) {
            c2.adjacent.add(c1);
        }
    }

    void bfs() {
        Queue<Computer> queue = new LinkedList<>();
        Computer root = computers[0]; // 1번 컴퓨터
        root.marked = true;
        queue.add(root);

        while (!queue.isEmpty()) {
						//queue에 들어있는 컴퓨터 꺼내서 방문
            Computer computer = queue.poll();
						// 인접한 컴퓨터가 있으면 큐에 담아준다
            for (Computer c : computer.adjacent) {
                if (c.marked == false) {
                    c.marked = true;
                    queue.add(c);
                }
            }
            visit(computer);
        }
    }

    void visit(Computer computer) {
				// 1번컴퓨터 제외
        if (computer.num != 1) {
            count += 1;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        sc.nextLine();
        int edges = sc.nextInt();
        sc.nextLine();
        Graph g = new Graph(size);
        for (int i = 0; i < edges; i++) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            g.addEdge(a, b);
            sc.nextLine();
        }

        g.bfs();
        System.out.print(g.count);
    }
}

'알고리즘 > 백준' 카테고리의 다른 글

[백준/java] 2606번 - 바이러스  (0) 2023.05.12
[백준1012/java] 유기농 배추  (0) 2023.05.12
[백준/java] 1260번 - DFS와 BFS  (1) 2023.05.12
[백준/java] 18259번 - 큐2  (0) 2023.05.12
[백준/java] 2164번 - 카드2  (0) 2023.05.12

- 문제 : https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

- 분류 : DFS, BFS

 

 

- 풀이

 

  • BFS (너비우선탐색)
    • 가까운 정점을 먼저 방문하는 구조이기 때문에, 가까운 정점을 저장해두고 순서대로 방문할 수 있도록 선입선출 구조인 Queue를 사용한다.

  • DFS (깊이우선탐색) 
    • 재귀 또는 스택을 사용해서 자기자신을 호출하는 순환 알고리즘 형태를 띈다.
    • 일단 한방향으로 갈 수 있는 데까지 깊이있게 파고든 다음에 다음으로 이동하는 방식.

 

 

import java.util.*;


class Node {
    int number; //정점 번호는 1번부터 N번까지
    LinkedList<Node> adjacent;
    boolean visited;
    
    public Node(int number) {
        this.number = number;
        this.visited = false;
        this.adjacent = new LinkedList<Node>();
    }
    
}

class Graph {
    Node[] nodes;
    
    public Graph(int nodeCount) {
        this.nodes = new Node[nodeCount];
        for(int i = 0; i<nodeCount; i++) {
            this.nodes[i] = new Node(i+1);
        }
    }
    
     public void addEdge(int a, int b) {
        Node aNode = this.nodes[a-1];
        Node bNode = this.nodes[b-1];
        
        if(!aNode.adjacent.contains(bNode)) {
            aNode.adjacent.add(bNode);
            // 여러개일 경우 작은 정점 먼저 방문하도록 정렬
            Collections.sort(aNode.adjacent, new Comparator<Node>() {
               @Override
               public int compare(Node a, Node b) {
                   return a.number > b.number ? 1: -1;
               }
            });
            
        }
        
        if(!bNode.adjacent.contains(aNode)) {
            bNode.adjacent.add(aNode);
            // 여러개일 경우 작은 정점 먼저 방문하도록 정렬
            Collections.sort(bNode.adjacent, new Comparator<Node>() {
               @Override
               public int compare(Node a, Node b) {
                   return a.number > b.number ? 1: -1;
               }
            });
        }
        
        
    }
    
    public void dfs(int v) {
        Node vNode = this.nodes[v-1];
        System.out.print(vNode.number + " ");
        vNode.visited = true;
        
        for(Node node: vNode.adjacent) {
            if(node.visited == false) {
                dfs(node.number);
            }
        }
    }

    public void bfs(int v) {
        Queue<Node> q = new LinkedList<Node>();
        Node vNode = this.nodes[v-1];
        q.add(vNode);
        vNode.visited = true;
      
        while(!q.isEmpty()){
            Node toVisit = q.peek();
            q.poll();
            System.out.print(toVisit.number + " ");
            
            if(!toVisit.adjacent.isEmpty()) {
                for(Node node : toVisit.adjacent) {
                    if(!node.visited) {
                        q.add(node);
                        node.visited = true;
                    }
                }
            } 
        }
    }
    
    //방문기록 초기화
    public void clearVisited() {
        for(Node node : this.nodes) {
            node.visited = false;
        }
    }

    
}



public class Main
{
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    
	    int nodeCount = sc.nextInt();
	    int edgeCount = sc.nextInt();
	    int v = sc.nextInt(); //startNode
	    
	    Graph g = new Graph(nodeCount);
	    
	    for(int i = 0; i<edgeCount; i++) {
	        int a = sc.nextInt();
	        int b = sc.nextInt();
	        
	        g.addEdge(a,b);
	    }
	    
	    g.dfs(v);
	   g.clearVisited();
	    System.out.println();
	    g.bfs(v);
	
	}
}

 

 

'알고리즘 > 백준' 카테고리의 다른 글

[백준1012/java] 유기농 배추  (0) 2023.05.12
[백준2606/java] 바이러스  (0) 2023.05.12
[백준/java] 18259번 - 큐2  (0) 2023.05.12
[백준/java] 2164번 - 카드2  (0) 2023.05.12
[백준/java] 2630번 - 색종이 만들기  (0) 2023.05.12

 

문제 : https://www.acmicpc.net/problem/18258

 

 

18258번: 큐 2

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 


풀이

 

문제 자체는 쉽다. Queue에 대한 기본 개념만 있으면 쉽게 구현할 수 있다.

다만 계속 '시간초과'가 떠서 이를 해결하는 데 초점을 맞춰야 한다.

 

시간초과를 해결하기 위해서는 아래 방법들이 있다.

 

1. 시간이 오래 걸리는 Scanner나 System.out.print() 대신 => BufferedReader, BufferedWriter를 사용한다

  • 입력된 데이터를 바로 전달되지 않고 buffer에 모았다가 한번에 전달하므로 데이터 처리 효율성을 높인다. 다만 입력받은 데이터를 전부 String타입으로 고정하기 때문에 다른 타입으로 변환하는 가공 작업이 필요하다.
import java.io.BufferedReader;
import java.io.InputStreamReader;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());

 

2. StringBuilder를 사용해서 output을 한번에 출력한다

 


코드 

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

class Queue{
	
	StringBuilder sb = new StringBuilder();
	LinkedList<Integer> list = new LinkedList<Integer>();

	public void push(int x) {
		list.add(x);
	}
	
	public void pop() throws IOException {
		//가장 앞에 있는 정수를 빼고 그 수를 출력한다
		//만일 큐에 들어있는 정수가 없으면 -1 출력
		sb.append(list.isEmpty()? "-1": list.poll());
		sb.append("\n");
    }
	
	public void size() throws IOException {
		//큐에 들어있는 정수의 개수를 출력한다
		sb.append(list.size() + "\n");
		
	}
	
	public void empty() throws IOException {
		//큐가 비어있으면 1, 아니면 0 출력
		sb.append(list.isEmpty()?"1":"0");
		sb.append("\n");
	}
    
	public void front() throws IOException {
		//가장 앞에 있는 정수를 출력
		//만약 큐에 들어있는 정수가 없으면 -1 출력
		sb.append(list.isEmpty() ? "-1" : list.getFirst());
		sb.append("\n");
		
	}
	public void back() throws IOException {
		//가장 뒤에 있는 정수를 출력
		//만약 큐에 들어있는 정수가 없는 경우 -1 출력
		sb.append(list.isEmpty()? "-1" : list.getLast());
		sb.append("\n");
	
	}
    
    public void print() {
        System.out.print(sb);
    }
}
public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		Queue q = new Queue();
		String command[] = new String[n];
		
		for(int i = 0; i<n; i++) {
			command[i] = br.readLine();
		}
		
		for(int i = 0; i<n; i++) {
			String tmp = command[i];
		
			switch(tmp) {
			case "front":
				q.front();
				break;
			case "pop":
				q.pop();
				break;
			case "size":
				q.size();
				break;
			case "empty":
				q.empty();
				break;
			case "back":
				q.back();
				break;
			default:
				String sx = tmp.substring(5);
				int x = Integer.parseInt(sx);
				q.push(x);
			}
		}
       
        q.print();
        br.close();
	}
}

 


참고자료


https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html

 

BufferedReader (Java Platform SE 8 )

Reads characters into a portion of an array. This method implements the general contract of the corresponding read method of the Reader class. As an additional convenience, it attempts to read as many characters as possible by repeatedly invoking the read

docs.oracle.com

https://jhnyang.tistory.com/92

 

[Java 자바 입출력] BufferedReader/BufferedWriter

[자바 입출력 함수] BufferedReader / BufferWriter BufferedReader/BufferedWriter은 이름처럼 버퍼를 이용해서 읽고 쓰는 함수입니다. 이 함수는 버퍼를 이용하기 때문에 이 함수를 이용하면 입출력의 효율이..

jhnyang.tistory.com

https://yeon-kr.tistory.com/152

 

(Java)ArrayList vs LinkedList 시간 복잡도

1) 서론 Selenium과 JSoup을 이용해서 크롤링을 하다 보면 데이터를 가지고 오고, 추가하는 작업을 많이 하게 됩니다. 그럴 때 반복적으로 사용하게 되는 것이 List 인터페이스와 For loop입니다. 하지만

yeon-kr.tistory.com

 

https://www.acmicpc.net/problem/2164

 

2164번: 카드2

N장의 카드가 있다. 각각의 카드는 차례로 1부터 N까지의 번호가 붙어 있으며, 1번 카드가 제일 위에, N번 카드가 제일 아래인 상태로 순서대로 카드가 놓여 있다. 이제 다음과 같은 동작을 카드가

www.acmicpc.net

- 분류 : Queue

 

아주 간단한 문제이다.

 

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		
		Queue<Integer> q = new LinkedList();
		for(int i = 0; i<n ; i++) {
		    q.add(i+1);
		}
		
		while(q.size() > 1) {
		    q.remove();
		    int head = q.poll();
		    q.add(head);
		}
		
		System.out.println(q.poll());
		
	}
}

+ Recent posts