[프로그래머스, Java] 최대공약수와 최소공배수
·
CodingTest/Programmers
💡풀이class Solution { public int[] solution(int n, int m) { // 유클리드 호제법을 사용하여 최대공약수와 최소공배수를 구하는 방법 int a = Math.max(n, m); int b = Math.min(n, m); while (b > 0) { int temp = a % b; a = b; b = temp; } int gcd = a; // 최대공약수 greatest common divisor int lcm = n * m / gcd; // 최소공배수 least common multiple return ..
[Java, Stack] 왜 Stack이 아닌 Deque로 스택을 구현해야 할까?
·
Backend/Java
Stack 클래스가 상속하고 있는 Vector가 문제가 되기 때문에 Deque 사용을 권장한다. ❌ Stack stack = new Stack();⭕ Deque stack = new ArrayDeque(); Vector는 자바 버전 1부터 있었던 굉장히 오래된 클래스이기 때문에 여러모로 취약점이 많다. 1️⃣Stack은 Vector를 상속받아 구현되어 있다.상속으로 부모 메서드를 공유하기 때문에 Stack을 사용자가 잘못되게 사용할 수 있는 문제가 발생한다.Vector에는 원하는 index에 객체를 끼워 넣을 수 있는 insertElementAt이라는 메서드가 존재한다.문제는 Stack이 Vector를 상속받았기 때문에 insertElementAt 사용이 가능하다는 점이다.후입 선출이 보장되어야 하..
[프로그래머스, Java] 같은 숫자는 싫어
·
CodingTest/Programmers
💡풀이- Stack 사용import java.util.*;public class Solution { public int[] solution(int []arr) { Stack stack = new Stack(); for(int n : arr){ if(stack.isEmpty() || stack.peek() != n){ stack.push(n); } } return stack.stream().mapToInt(Integer::intValue).toArray(); }}💡풀이 2- Stack을 ArrayDeque로 구현import java.util.*;import jav..
[프로그래머스, Java] 직사각형 별찍기
·
CodingTest/Programmers
💡풀이import java.util.Scanner;class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); for (int i = 0; i 💡풀이 2- StringTokenizer, BufferedReader, BufferedWriter 사용해서 풀어보기 (속도 향상)import java.io.*;import java.util.StringTokenizer;class Solution { public static void main(String[] args)..
[프로그래머스, Java] 행렬의 덧셈
·
CodingTest/Programmers
💡풀이class Solution { public int[][] solution(int[][] arr1, int[][] arr2) { int answer[][] = new int[arr1.length][arr1[0].length]; for (int i = 0; i GitHub - okjunghyeon/Programmers_CodingTest: 프로그래머스 관련 코딩테스트 문제를 풀이한 저장소입니다.프로그래머스 관련 코딩테스트 문제를 풀이한 저장소입니다. Contribute to okjunghyeon/Programmers_CodingTest development by creating an account on GitHub.github.com
[프로그래머스, Java] 문자열 다루기 기본
·
CodingTest/Programmers
💡풀이- toCharArray() 활용class Solution { public boolean solution(String s) { for (char c : s.toCharArray()) { if(!Character.isDigit(c)) return false; } return s.length() == 4 || s.length() == 6; }}💡풀이 2- chars() 스트림 활용class Solution { public boolean solution(String s) { return s.chars().allMatch(Character::isDigit) ..