본문 바로가기

알고리즘

중복없는구간

import java.util.Scanner;
import java.util.ArrayList;
public class Main{
    public static int n;
    public static int[] arr;
    public static int[] v;
    public static void main(String[] args){

      Scanner scan = new Scanner(System.in);
      n = scan.nextInt();
      arr = new int[n+1];
      v = new int[n+1];
      for(int i=1;i<=n;i++)arr[i]=scan.nextInt();
      bSearch(1,n);
      
      scan.close();
    }
    
    public static void bSearch(int s,int e)
    {
      
      int start=s;
      int end=e;
      if(check(end)){System.out.println(end);return;}
      while(start+1<end)
      {
        int mid = (start+end)/2;
        if(check(mid))start=mid;//만약 중복구간이 되면 (위로 올려야지)
        else end=mid;
      }
      System.out.println(start);
    }
    
    public static boolean check(int interval)
    {
      ArrayList<Integer> arrList = new ArrayList();
      int cnt=0;
      for(int i=1;i<=n;i++)
      {
        if(v[arr[i]]==0)
        {
          cnt+=1;
          v[arr[i]]=i;
          arrList.add(arr[i]);
        }
        else
        {
          cnt=0;
          int x = v[arr[i]];
          i=x;
          
          for(int k=0;k<arrList.size();k++)
          {
            int t = arrList.get(k);
            v[t]=0;
          }
          arrList.clear();
        }
        if(cnt==interval)
        {
          for(int k=0;k<arrList.size();k++)
          {
            int t = arrList.get(k);
            v[t]=0;
          }
          arrList.clear();
          return true;
        }
      }
      
     for(int k=0;k<arrList.size();k++)
        {
          int t = arrList.get(k);
          v[t]=0;
        }
        arrList.clear();
      
      return false;
    }
}

'알고리즘' 카테고리의 다른 글

미로 탐색  (0) 2019.08.09
유기농 배추  (0) 2019.08.09
직사각형배치경우의수  (0) 2019.08.02
rook  (0) 2019.08.02
maxofarr  (0) 2019.08.01