본문 바로가기

분류 전체보기

(86)
[Easy] 704. Binary Search Leetcode 704번 문제는 integer array와 target value가 주어지면 binary search (이진 탐색)을 사용해 target value를 찾아내는 문제이다. 이진 탐색을 사용해야 하기 때문에 너무나 당연하지만 풀이 과정에서 time complexity (시간 복잡도)는 O(log n) 이 돼야 한다. #풀이 class Solution { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left nums[mid]){ left = mid + 1; } else if(target < nums[mid]){ right = mid - 1; } } return -1; } }..
[Easy] 344. Reverse String Leetcode 344번 문제는 단순히 주어진 문자열을 뒤집는 문제이다. 단 Space complexity (공간 복잡도) 가 O(1) 이 되도록 해야 한다. class Solution { public void reverseString(char[] s) { int i = 0, j = s.length - 1; while(j > i){ char temp = s[j]; s[j--] = s[i]; s[i++] = temp; } } }
[Medium] 2. Add Two Numbers Leetcode 2번 문제는 순서가 거꾸로 된 2개의 연결 리스트를 더하는 문제이다. 연결 리스트의 각 노드 들은 한자리 숫자 만을 가지고 있다. public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode sentinel = new ListNode(0); ListNode current = sentinel; int sum = 0; while (l1 != null || l2 != null) { sum /= 10; if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } current.nex..
[Easy] 234. Palindrome Linked List Leetcode 234번 문제는 주어진 linkedlist 가 palindrome(회문) 인지 아닌지 판단하는 문제이다. 여기서 palindrome은 거꾸로 읽어도 똑바로 읽어도 같은 문자열이다. 예)기러기, 토마토, 스위스, 인도인, 별똥별, 우영우. #ArrayList 사용법 class Solution { public boolean isPalindrome(ListNode head) { ArrayList al = new ArrayList(); ListNode current = head; while(current !=null){ al.add(current.val); current = current.next; } int i = 0, j = al.size() - 1; while(i < j){ if(al.ge..
[Easy] 1. Two Sum Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Leetcode 1번 문제 Two Sum에서는 하나의 배열과 하나의 target value 가 주어지며, 배열에서 두 개의 값을 더했을때 target value와 같아지는 index를 가지고있는 배열을 반환하는 문제이다. #Brute force 방식 O(n^2) class Sol..
[EASY] 27. Remove Element #문제 설명 Leetcode 27번 문제는 integer array와 target value가 주어져, array에서 target value를 제외한 k개의 element를 return 하면 된다. 또한 k-1 index 이후에는 결과에 아무 element나 있으면 된다. 예를 들어 input으로 다음과 같은 값이 주어졌다고 가정하자. Input: nums = [3,2,2,3], val = 3 그럼 target value인 3을 제외하면 배열은 다음과 같이 변경 해야 한다. Output: 2, nums = [2,2,_,_] 처음 3을 제외하면 배열은 [_,2,2,_] 이 되고 2개의 element, 즉 k = 2가 된다. 하지만 k-1 인 index 1 이후에는 값이 있으면 안되기에 [2,2,_,_] 처..