Light Blue Pointer
본문 바로가기
Hacks

Java hacks for Coding test

by 개발바닥곰발바닥!!! 2023. 12. 15.

하나하나 import x

import java.util.*; → 풀다가 자료구조 바꿀때도 새로 안 써도 돼서 시간 은근 절약됨 꿀팁

Character

⭐how to know if a character is lowercase

Character.isLowerCase('c');

⭐how to convert lowercase to uppercase

Character.toUpperCase(f);

⚠️주의할 점은 저거 하고 다시 넣어줘야 한다는거다 substring같이

char c = s.charAt(0);
Character.toUpperCase(c); -> 바뀐게 c에 저장이 안 됨
c = Character.toUpperCase(c); -> 넣어줘야 함!

String

⭐String이 Char을 포함하는지 아는법

skip.contains(String.valueOf(temp)

⭐String끼리 +연산 하는게 상당히 느리기 때문에 Stringbuilder로 만들고 .append()를 해줄것!

⭐Public String [] split ( String regex, int limit)

  • limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times, the resulting array’s length will not be more than n, and the resulting array’s last entry will contain all input beyond the last matched pattern.
  • limit < 0 – In this case, the pattern will be applied as many times as possible, and the resulting array can be of any size.
  • limit = 0 – In this case, the pattern will be applied as many times as possible, the resulting array can be of any size, and trailing empty strings will be discarded.

Let the string that is to be split is – geekss@for@geekssd

Regex Limit Result

@ 2 {“geekss”, ”for@geekss”}
@ 5 {“geekss”, ”for”, ”geekss”}
@ -2 {“geekss”, ”for”, ”geekss”}
s 5 {“geek”, ”“, “@for@geek”, “”, “”}
s -2 {“geek”, ” “, ” “, “@for@geek”, “”, “”}
s 0 {“geek”, ””, ”@for@geek”}

⭐Java Split dot(".") → ("\\.") Regex에 해당되어서 바꿔줘야 함

str.split("."); → str.split("\\\\.");
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("@", 2);
/* result
geekss
for@geekss
*/

String str = "geekss@for@geekss";
String[] arrOfStr = str.split("@", -2);
/* result
geekss
for
geekss
*/

String str = "GeeksforGeeks:A Computer Science Portal";
String[] arrOfStr = str.split(":");
/* result
GeeksforGeeks
A Computer Science Portal
*/

String str = "word1, word2 word3@word4?word5.word6";
String[] arrOfStr = str.split("[, ?.@]+");
/* result
word1
word2
word3
word4
word5
word6
*/

⭐java String to charArray

String s = "GeeksForGeeks";
char[] gfg = s.toCharArray();

⚠️replace하고 String에 안 넣어주시면 안됩니다

Y.replaceFirst(target,"");

→

Y = Y.replaceFirst(target,"");

Map

⭐HashMap의 getOrDefault

int result = map.getOrDefault(target,-1);

⭐How to update a value, given a key in a hashmap?

map.put(key, map.get(key) + 1);

⭐how to remove entry from hashmap by Value?

There's a simple method, but it'll use iteration internally. 
(There's no way around that.)

map.values().remove(valueToRemove);
//근데 그냥 map.remove(key) 썼던거같아 아 이건 value로 제거하기구나 count가 일정 수 이상인거 날려버릴때 썼던듯 인데? 
걍 List로 바꿔서 보면서 value가 count 넘는 key를 갖다 삭제하면 될 것 같음

⭐람다 함수로 map 정렬하기

Map<String, Integer> map = new HashMap<>();
map.put("a", 3);
map.put("b", 2);
map.put("c", 1);

//정렬
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
entryList.sort(((o1, o2) -> map.get(o1.getKey()) - map.get(o2.getKey())));

//출력for(Map.Entry<String, Integer> entry : entryList){
    System.out.println("key : " + entry.getKey() + ", value : " + entry.getValue());
}
sort 함수 내가 구현해도 되는데 -1 0 1이 돌아가야 함, 외부 함수여도 상관 x

Map을 ArrayList로!

List<Map.Entry<Integer,Integer>> = new ArrayList<>(**a.entrySet()**); //->
entry.getKey()
entry.getValue()

Map Iteration

for(Map.Entry<Integer,Integer> val : map.entrySet()){
                int left = val.getKey() +cost[index];
                int right = val.getKey();

                if (left >= max) next.add(left);
                if (right >= max) next.add(right);
            }

List

⭐List 의 정렬

Lambda함수로 정렬하기

list.sort((s1, s2) -> s2.compareTo(s1)); // 리스트에 있는 값을 내림차순으로 정렬

Comparator로 List 정렬하기

class Cost implements Comparable<Cost>{
    public int cost;
    
    public int compareTo(Cost c)
    {
        if (cost > c.cost) {
            return 1;
        }
        else if (cost == c.cost) {
            return 0;
        }
        else {
            return -1;
        }
    }
}
public class Main {
    // Main driver method
    public static void main(String[] args)
    {
        // . . .
        Collections.sort(costs);
    }
}

ArrayList

Swap⭐

import java.util.Collections;

**Collections.swap(ArrList, 1, 2);**

Stack

import java.util.Stack;

Stack<Integer> stack = new Stack<Integer>();
stack.push(value);//Pushes an element on the top of the stack.
int position = stack.search(value);//If the element is found, returns the position of the element from the top of the stack. Else, it returns -1.
stack.pop();//Removes and returns the top element of the stack. An ‘EmptyStackException’ is thrown if we call pop() when the invoking stack is empty.
stack.peek();//Returns the element on the top of the stack, but does not remove it.
stack.empty(); //It returns true if nothing is on the top of the stack. Else, returns false.

⚠️stack search는 0이 아니라 1부터 세어줌

Set

import java.util.HashSet; // Import the HashSet class

HashSet<String> cars = new HashSet<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("BMW");
    cars.add("Mazda");
    System.out.println(cars);

cars.contains("Mazda");
cars.remove("Volvo");
cars.clear();

Set To List in Constructor

Set<Integer> a = new HashSet<>();
        a.add(1);
        a.add(2);
        a.add(3);
        a.add(1);

List<Integer> arr = new ArrayList<>(a);

Set Iteration with improved for loop

HashSet<Integer> set = new HashSet<>();

for(int val : set){
                int left = val/3;
                int right = val/2;
                int middle = val -1;

                if (val%3==0&& left >= target) next.add(left);
                if (val%2==0&& right >= target) next.add(right);
                if(middle>=target) next.add(middle);
            }

Queue

// Java program to demonstrate a Queue
 
import java.util.LinkedList;
import java.util.Queue;

Queue<Integer> q = new LinkedList<>();
 
        for (int i = 0; i < 5; i++)
            q.add(i);

        int removedele = q.remove();
        int head = q.peek();
         int size = q.size();

}

Priority Queue

compareTo구현 안 해도 lambda로도 가능함

PriorityQueue<Integer> q = new PriorityQueue<>((o1,o2)-> o2-o1);
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

where E is the type of elements held in this queue

A few important points on Priority Queue are as follows:

PriorityQueue<E> pq = new PriorityQueue<E>();//natural ordering
PriorityQueue<E> pq = new PriorityQueue<E>(Collection<E> c);
3. PriorityQueue(int initialCapacity): Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.

PriorityQueue<E> pq = new PriorityQueue<E>(int initialCapacity);

4. PriorityQueue(int initialCapacity, Comparator<E> comparator): Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.

PriorityQueue<E> pq = new PriorityQueue(int initialCapacity, Comparator<E> comparator);

5. PriorityQueue(PriorityQueue<E> c): Creates a PriorityQueue containing the elements in the specified priority queue.

PriorityQueue<E> pq = new PriorityQueue(PriorityQueue<E> c);

6. PriorityQueue(SortedSet<E> c): Creates a PriorityQueue containing the elements in the specified sorted set.

PriorityQueue<E> pq = new PriorityQueue<E>(SortedSet<E> c);

7. PriorityQueue(Comparator<E> comparator): Creates a PriorityQueue with the default initial capacity and whose elements are ordered according to the specified comparator.

PriorityQueue<E> pq = new PriorityQueue<E>(Comparator<E> c);
import java.util.*;
 
class PriorityQueueDemo {
   
      // Main Method
    public static void main(String args[])
    {
        // Creating empty priority queue
        PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
 
        // Adding items to the pQueue using add()
        pQueue.add(10);
        pQueue.add(20);
        pQueue.add(15);
 
        // Printing the top element of PriorityQueue
        System.out.println(pQueue.peek());
 
        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pQueue.poll());
 
        // Printing the top element again
        System.out.println(pQueue.peek());
    }
}

내가 원하는 Class 구현해서도 사용가능함, compareTo 를 구현해 줘야 함

import java.util.*;

class Solution {
    public int solution(int n, int k, int[] enemy) {
        int answer = 0;
        
        PriorityQueue<Enemy> q = new PriorityQueue<>();
        
        for(int i=0;i<enemy.length;i++){
            
            q.add(new Enemy(enemy[i],i));
            
            if(n-enemy[i]<0){
                if(k>0){
                    Enemy temp = q.poll();
                    ...
                }
            }
            
...
   
        }

        return answer;
    }
}

class Enemy implements Comparable<Enemy>{
    public int number;
    public int index;
    
    public Enemy(int n, int i){
        number = n;
        index = i;
    }
    
    public int compareTo(Enemy o){
        return o.number - this.number;
    }
}

다른 자료구조 혼종으로 쓰기

ArrayList의 배열

static ArrayList<Node> [] nodes;

nodes = new ArrayList [n]; //new ArrayList<Integer> []이 아님에 주의!

배열의 ArrayList

private static List<int[]> list;
list = new ArrayList<>();
list.add(new int[] {start, end});

Array

deep copy

boolean [] newVisit = visit.clone();

sort with lambda

Arrays.sort(a,(o1,o2)->o2-o1);