yeahzzz
archive
yeahzzz
전체 방문자
오늘
어제
  • 분류 전체보기 (164)
    • Language (41)
      • Python (12)
      • JAVA (21)
      • C&C++ (8)
    • Algorithms (25)
      • programmers (9)
      • study log (16)
    • Problems & Solutions (14)
    • Major (29)
      • Data Structure & Algorithm (14)
      • Linux(Ubuntu) (9)
      • Security (2)
      • Linear Algebra (4)
    • FE (44)
      • Web(HTML5, CSS, JS) (5)
      • React & TS (26)
      • 코딩일기 (10)
    • BE (1)
      • Node.js (1)
    • Pytorch (8)
    • Server (2)

블로그 메뉴

  • 홈

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
yeahzzz
Algorithms/study log

[투포인터] 백준 20922 겹치는 건 싫어

Algorithms/study log

[투포인터] 백준 20922 겹치는 건 싫어

2024. 4. 9. 17:18

 

 

20922번: 겹치는 건 싫어

홍대병에 걸린 도현이는 겹치는 것을 매우 싫어한다. 특히 수열에서 같은 원소가 여러 개 들어 있는 수열을 싫어한다. 도현이를 위해 같은 원소가 $K$개 이하로 들어 있는 최장 연속 부분 수열

www.acmicpc.net

 

시간초과 코드

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());
        int[] arr = new int[n];
        int[] check = new int[100001];
        st = new StringTokenizer(br.readLine());
        for(int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        
        int start = 0;
        int end = 1;
        int count = 1;
        int max = 0;
        check[arr[start]]++; 
        while(true) {
        	check[arr[end]]++; 
        	if(check[arr[end]] <= k) {
        		end++;
        		count++;
        		max = Math.max(count, max);
        	}
        	else if(check[arr[end]] > k) { //예외 
        		start=end+1;
        		max = Math.max(count, max);
        		count=1;
        		
        	}
        	if(end==n-1 || start==n-1) break;
        }
        System.out.println(max);
    }
}

각 숫자가 등장한 횟수를 체크하는 check 배열 사용.

IDE에서는 잘 나왔지만 시간초과가 발생했다. 시작점인 start를 불필요하게 갱신하며, end의 범위 설정에 문제가 있다.

 

 

개선된 코드(투포인터)

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());
        int[] arr = new int[n];
        int[] check = new int[100001];
        st = new StringTokenizer(br.readLine());
        for(int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        
        int start = 0, end = 0, max = 0;
        while(end < n) {
            if(check[arr[end]] < k) {
                check[arr[end]]++;
                end++;
            } else {
                
                check[arr[start]]--;
                start++;
            }
            max = Math.max(max, end - start);
        }
        System.out.println(max);
    }
}

현재 end 위치의 숫자가 k번을 초과하면, start 위치의 숫자 등장 횟수를 줄이고 start를 오른쪽으로 이동시킨다.

그리고 end-start로 수열의 최대 길이를 갱신시켜줌.

저작자표시

'Algorithms > study log' 카테고리의 다른 글

[Graph+BFS] 백준 7576 토마토  (0) 2024.04.14
그래프 이론 톺아보기  (0) 2024.04.14
[백트래킹] 눈덩이 굴리기, 근손실, 1,2,3 더하기 2  (1) 2024.04.07
[Greedy] 백준 2141 우체국  (0) 2024.03.19
[Greedy] 연속되는 조건이 있는 문제  (1) 2024.03.17
    'Algorithms/study log' 카테고리의 다른 글
    • [Graph+BFS] 백준 7576 토마토
    • 그래프 이론 톺아보기
    • [백트래킹] 눈덩이 굴리기, 근손실, 1,2,3 더하기 2
    • [Greedy] 백준 2141 우체국
    yeahzzz
    yeahzzz

    티스토리툴바

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.