[해커랭크] [Easy] Java List

2021. 5. 25. 23:24알고리즘/해커랭크

728x90
반응형
SMALL

For this problem, we have  types of queries you can perform on a List:

  1. Insert y at index x :
    Insert
    x y
  2. Delete the element at index :
    Delete 
    x

Given a list, L, of N integers, perform Q queries on the list.

Once all queries are completed, print the modified list as a single line of space-separated integers.

 

Input Format

The first line contains an integer,  N (the initial number of elements in L).
The second line contains N space-separated integers describing L.
The third line contains an integer,  Q(the number of queries).
The 2Q subsequent lines describe the queries, and each query is described over two lines:

  • If the first line of a query contains the String Insert, then the second line contains two space separated integers x y, and the value  must be inserted into L at index x.
  • If the first line of a query contains the String Delete, then the second line contains index , whose element must be deleted from L.

Constraints

  • 1 ≤ N ≤ 4000
  • 1 ≤ Q ≤ 4000
  • Each element in is a 32-bit integer.

 

Output Format

Print the updated list L as a single line of space-separated integers.

 

Sample Input

5
12 0 1 78 12
2
Insert
5 23
Delete
0

 

Sample Output

0 1 78 12 23

 

Explanation

Having performed all  queries, we print  as a single line of space-separated integers.

 

 

🌈 Solution.java

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
import java.io.*;
import java.util.*;
 
public class Solution {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        int N = sc.nextInt();
 
        List<Integer> list = new ArrayList<Integer>();
 
        for (int i = 0; i < N; i++) {
            list.add(sc.nextInt());
        }
 
        int Q = sc.nextInt();
        for (int i = 0; i < Q; i++) {
            String query = sc.next();
            switch (query) {
            case "Insert":
                list.add(sc.nextInt(), sc.nextInt());
                break;
            case "Delete":
                list.remove(sc.nextInt());
                break;
            }
        }
        
        sc.close();
        
        for (Integer integer : list) {
            System.out.print(integer +" ");
        }
    }
}
cs

 

👩‍💻 풀어보기 👨‍💻 https://www.hackerrank.com/challenges/java-list/problem

 

Java List | HackerRank

 

www.hackerrank.com

 

728x90
반응형
LIST

'알고리즘 > 해커랭크' 카테고리의 다른 글

[해커랭크] [Easy] Java 1D Array  (0) 2021.03.10