자바 백준 7785번 회사에 있는 사람
회사에 동명이인이 없다는 부분에서 LIST가 아니라 SET이 쓰는 것이 맞다.
LIST를 사용한 코드와 SET을 사용한 코드 둘 다 업로드 하려고 한다.
LIST 같은 경우에는 인덱스로 객체를 관리하기 때문에 get으로 이래저래해서 답을 쉽게 얻을 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
ArrayList<String> list = new ArrayList<String>(); | |
Scanner sc = new Scanner(System.in); | |
int num = sc.nextInt(); | |
for(int i=0; i<num; i++) { | |
String people = sc.next(); | |
String inout = sc.next(); | |
if(inout.equals("enter")) { | |
list.add(people); | |
}else { | |
list.remove(people); | |
} | |
} | |
Collections.sort(list); | |
for(int i=list.size()-1; i>=0; i--) { | |
System.out.println(list.get(i)); | |
} | |
sc.close(); | |
} | |
} |
Set은 인덱스로 객체를 관리하지 않기 때문에 데이터를 검색하기 위해서는 iterator() 메서드로 Iterator(반복자)를 생성하고 데이터를 가져와야 한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.StringBuilder; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.*; | |
public class Main { | |
static int n; | |
static StringBuilder sb; | |
static StringTokenizer st; | |
public static void main(String[] args) throws IOException { | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
n = Integer.parseInt(br.readLine()); | |
StringBuilder sb = new StringBuilder(); | |
Set<String> set = new TreeSet<>(); | |
while(n > 0){ | |
st = new StringTokenizer(br.readLine()); | |
String name = st.nextToken(); | |
String a = st.nextToken(); | |
if(a.equals("enter")){ | |
set.add(name); | |
} | |
else{ | |
set.remove(name); | |
} | |
n--; | |
} | |
for(Iterator<String> itr = ((TreeSet<String>) set).descendingIterator(); itr.hasNext();){ | |
sb.append(itr.next()).append("\n"); // set을 역순으로 읽음. | |
} | |
System.out.println(sb.toString()); | |
} | |
} | |
'백준 알고리즘 > JAVA' 카테고리의 다른 글
자바 백준 3653번 영화 수집 (0) | 2018.08.14 |
---|---|
자바 백준 9375번 패션왕 신해빈 (0) | 2018.08.13 |
자바 백준 1357번 뒤집힌 덧셈 (0) | 2018.08.10 |
자바 백준 2864번 5와 6의 차이 (0) | 2018.08.08 |
자바 백준 1652번 누울 자리를 찾아라 (0) | 2018.08.07 |