본문 바로가기

[JAVA] LeetCode 387 - First Unique Character in a String Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. 문자열이 주어지면, 반복되지 않는 가장 첫번째 문자 찾아 인덱스를 반환하라. 만약 존재하지 않는다면, -1을 반환하라. 풀이 방법 1. 총 26개 알파벳의 카운트 값을 담을 배열 alpha를 선언한다. 2. 문자열의 길이만큼 반복문을 수행하며, 한 글자씩 파싱한다. 3. 파싱된 문자의 아스키코드 값 - 97을 하여, 해당 알파벳의 카운팅을 수행한다. 4. 다시 문자열의 길이만큼 반복문을 수행하며, 카운트가 1인 알파벳의 인덱스를 반환한다. 5. 카운트가 1인 알파벳이 없을 경우, 반복문을 마친 후 -1..
[JAVA] LeetCode 118 - Pascal's Triangle Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. 음수가 아닌 정수 numRows가 주어지면, 파스칼 삼각형을 만들어라. 파스칼 삼각형에서 각 숫자는 그 바로 위에 있는 두 숫자의 합이다. 풀이 방법 문제 그대로 2중 반복문으로 파스칼 삼각형을 만들면 된다. 핵심 풀이 방법은 다음과 같다. 1. 현재 입력해야 하는 인덱스가 라인의 양 끝일 경우 1을 입력한다. 2. 라인의 양 끝이 아닐 경우, 값을 구하기 위해 이전 라인에 있던 리스트 객체를 받아온다. ..
[JAVA] LeetCode 21 - Merge Two Sorted Lists Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example 1: 두 개의 정렬된 연결 리스트를 병합하여 하나의 새로운 정렬된 리스트로 반환하라. 새로운 리스트는 주어진 두 개의 연결 리스트 노드를 함께 분할하여 만들어야 한다. 풀이 방법 1. 루트 노드와 초기에 생성한 루트 노드의 주소를 가지는 head 노드를 만든다. 2. 주어진 연결 리스트(l1,l2)가 모두 null이 될 때까지(마지막 노드까지 탐색), 반복문을 수행한다. 3. val1과 val2에 각각 현재 리스트(l1, l2)..
[JAVA] LeetCode 122 - Best Time to Buy and Sell Stock II Say you have an array prices for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). i일(day)에 주식의 가격이 적힌 ..
[JAVA] LeetCode 217 - Contains Duplicate Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 정수형 배열이 주어지면, 배열에 중복된 항목이 있는지 찾아라. 배열에 값이 두 번 이상 나타나면 함수가 true를 반환해야 하고, 모든 항목이 중복되지 않으면 false를 반환해야 한다. 풀이 방법 중복 되지 않는 값을 저장하는 Set을 이용하여 풀이하기! 1. 배열의 길이만큼 반복문을 수행하며, HashSet에 값이 존재할 경우 t..
[JAVA] LeetCode 171 - Excel Sheet Column Number Given a column title as appear in an Excel sheet, return its corresponding column number. 엑셀 시트에 나타나는 열 타이틀이 주어지면, 해당 열의 번호를 반환하라. Example 1:Input: "A" Output: 1 Example 2: Input: "AB" Output: 28 Example 3: Input: "ZY" Output: 701 풀이 방법 예제로 주어진 Input과 Output을 분석해보면, 각 문자의 인덱스 별 열 번호를 공식을 만들 수 있다. 나의 경우, 26^(문자열의 길이 - 현재 문자의 인덱스) * (현재 문자의 번호) 라는 공식을 만들었고, 현재 문자의 번호는 char 타입의 문자(아스키 코드)에서 - 64를 하..
[JAVA] LeetCode 108 - Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 오름차순으로 정렬된 배열을 균형 이진 트리로 변환하라 균형 이진 트리는 두 하위 트리의 깊이(depth)가 1이 넘게 차이나지 않는 것을 의미힌다. 풀이 방법 1. 배열의 중앙 인덱스(mid)를 루트 노드로 생성한다. 2. 배열의 시작 인덱스(0)부터 m..
[JAVA] LeetCode 206 - Reverse Linked List Reverse a singly linked list. 단일 연결 리스트를 뒤집어라. 풀이 방법 1. reverse된 결과를 리턴 할 ListNode 타입의 node를 선언한다. 2. 시작 노드부터 마지막 노드까지 각 노드가 순차적으로 head가 되어 반복문을 수행한다. 3. head 노드를 변경하기 전에 저장해 둔 temp 노드의 next값에 node를 할당한다. 4. 글로 백 번 적는 것보다, 한 번 그림으로 그리면서 로직을 따라가면 더 확실히 이해가 될 것이다! class Solution { public ListNode reverseList(ListNode head) { ListNode node = null; while(head != null) { ListNode temp = head; head = ..