35. Search Insert Position

문제 정의
주어진 정렬된 배열에서 목표 값을 찾고, 찾지 못하면 목표 값이 삽입될 인덱스를 반환하는 문제입니다. 이 문제는 O(log n) 시간 복잡도로 해결해야 합니다.
https://leetcode.com/problems/search-insert-position/description/
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output : 2
Example 2:
Input: nums = [1,3,5,6], target =2
Output : 1
Example 3:
Input : nums = [1,3,5,6], target = 7
Output : 4
접근 방법 소개
처음에는 순차 접근 방식을 사용하여 문제를 해결했습니다. 하지만 이 방식은 O(n) 시간 복잡도를 가지며, 이는 문제의 요구사항인 O(log n)에 부합하지 않습니다.
class Solution { public int searchInsert(int[] nums, int target) { for(int i=0; i<nums.length; i++) { if (nums[i] == target) { return i; } if (target <nums[i]) { return i; } } return nums.length; } }
다음으로, 이진 탐색을 사용하여 문제를 해결했습니다. 이진 탐색은 O(log n) 시간 복잡도를 가지며, 대규모 데이터 처리에 매우 효율적입니다.
class Solution { public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return left; } }
이진 탐색 알고리즘 상세 설명
이진 탐색은 배열의 중간 값을 선택하여 목표 값과 비교하고, 목표 값이 더 크면 오른쪽 절반을, 더 작으면 왼쪽 절반을 다시 검색하는 방식입니다. 이렇게 반복함으로써 검색 범위를 절반으로 줄여나갑니다.
- 초기화: left와 right 변수를 배열의 처음과 끝으로 설정합니다.
- 중간값 계산: mid 변수를 left와 right의 중간값으로 설정합니다.
- 비교: nums[mid]가 target과 같으면 mid를 반환합니다. nums[mid]가 target보다 작으면 left를 mid + 1로, nums[mid]가 target보다 크면 right를 mid - 1로 설정합니다.
- 반복 종료: left가 right보다 커지면 반복을 종료하고, left를 반환합니다.
테스트 케이스 및 결과 검증
빈 배열 int[] nums = {}; int target = 5; // Expected output: 0 배열의 첫번째 위치에 삽입 int[] nums = {2, 3, 5, 6}; int target = 1; // Expected output: 0 배열의 마지막 위치에 삽입 int[] nums = {2, 3, 5, 6}; int target = 7; // Expected output: 4 배열의 중간에 삽입 int[] nums = {2, 4, 6, 8}; int target = 5; // Expected output: 2 목표 값이 배열의 모든 요소와 일치 int[] nums = {2, 2, 2, 2}; int target = 2; // Expected output: 0 배열의 경계 값 int[] nums = {2, 4, 6, 8}; int target = 2; // Expected output: 0 int[] nums2 = {2, 4, 6, 8}; int target2 = 8; // Expected output: 3 테스트 코드 class Solution { public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return left; } public static void main(String[] args) { Solution sol = new Solution(); // Edge case 1: 빈 배열 System.out.println(sol.searchInsert(new int[]{}, 5)); // Expected output: 0 // Edge case 2: 배열의 첫번째 위치에 삽입 System.out.println(sol.searchInsert(new int[]{2, 3, 5, 6}, 1)); // Expected output: 0 // Edge case 3: 배열의 마지막 위치에 삽입 System.out.println(sol.searchInsert(new int[]{2, 3, 5, 6}, 7)); // Expected output: 4 // Edge case 4: 배열의 중간에 삽입 System.out.println(sol.searchInsert(new int[]{2, 4, 6, 8}, 5)); // Expected output: 2 // Edge case 5: 목표 값이 배열의 모든 요소와 일치 System.out.println(sol.searchInsert(new int[]{2, 2, 2, 2}, 2)); // Expected output: 0 // Edge case 6: 배열의 경계 값 System.out.println(sol.searchInsert(new int[]{2, 4, 6, 8}, 2)); // Expected output: 0 System.out.println(sol.searchInsert(new int[]{2, 4, 6, 8}, 8)); // Expected output: 3 } }
'알고리즘' 카테고리의 다른 글
DAG, 위상정렬(feat. BOJ. 줄세우기) (0) | 2024.08.18 |
---|---|
알고리즘 펜윅 트리 (2) | 2024.08.11 |
979. Distribute Coins in Binary Tree (0) | 2024.05.19 |
밀렸던 릿코드 풀기 (232, 150, 739, 2966, 1291) (0) | 2024.02.03 |
kakao_광고삽입 (0) | 2021.12.06 |
댓글
이 글 공유하기
다른 글
-
DAG, 위상정렬(feat. BOJ. 줄세우기)
DAG, 위상정렬(feat. BOJ. 줄세우기)
2024.08.18위상정렬위상정렬(Topological Sorting)은 방향성 비순환 그래프(Directed Acyclic Graph, DAG)의 노드들을 선형으로 정렬하는 알고리즘입니다. 이 정렬은 그래프의 모든 간선이 방향성에 맞도록 순서대로 나열되도록 합니다.DAG = 사이클이 없는 방향 있는 그래프를 의미합니다. 선행그래프 구조를 가지고 있습니다.DAG 에서 할 수 있는 알고리즘은 위상정렬 알고리즘이 활용됩니다. BFS 알고리즘을 응용해서 구현할 수 있습니다.위상정렬에서 주목해서 봐야할 것은 순서와 큐 입니다. 이 상태에서 인디그리가 0인 상태인 얘들을 큐에 넣어줍니다. 큐 : 1,2,3 이 존재하고 (왜냐하면 1,2,3 노드로 들어오는 화살표가 0) 여기서 하나씩 빼면서 BFS 과정을 거쳐주게 됩니다.순서 :… -
알고리즘 펜윅 트리
알고리즘 펜윅 트리
2024.08.11시작펜윅 트리, 세그먼트 트리에서 변형된 형태입니다. 대표적으로 구간 합 알고리즘을 O(N)보다 빠르게 풀고자 할 때 펜윅 트리를 사용합니다.일반적으로 구간 합을 구할 때 O(N) 정도의 시간이 걸립니다.펜윅 트리(BIT = Binary Indexed Tree) 이용하게 되면 O(logN) 으로 시간 복잡도를 감소 시킬 수 있습니다. 전체 노드의 부분 합 즉, 0~K 합을 구해 두게 되면 원하는 구간 합 S~D를 구하는 것이 가능해 집니다. (Start ~ Destination)O(logN) 의 수행시간 만으로 구간합을 구할 수 있게 됩니다. 구간 합 외에도 같은 원리로 업데이트도 수행할 수 있게 됩니다. 펜윅트리 구조일반적으로 펜윅 트리 구조는 아래와 같이 세그먼트 트리를 응용한 형태로 구조를 정형화… -
979. Distribute Coins in Binary Tree
979. Distribute Coins in Binary Tree
2024.05.19You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.Return the minimum number of moves required to make every node have exactly one coin.Example 1… -
밀렸던 릿코드 풀기 (232, 150, 739, 2966, 1291)
밀렸던 릿코드 풀기 (232, 150, 739, 2966, 1291)
2024.02.03릿코드 문제가 영어라 접근하기 쉽지 않지만 그래도 풀어보면 자료구조에 대해 이해할 수 있어서 좋은점이 많다. 첫문제는 비교적 쉬운 문제이다. 232. Implement Queue using Stacks 처음에 접근할 때는 HashSet 을 사용해보려고 했는데 순서가 보장이 안되더라… 왜냐하면 내부적으로 해시테이블을 구현하는데 해시함수에 의해서 순서가 달라진다. LinkedHashSet을 이용하면 풀 수 있을거 같다.(+ 정렬되어있다면 TreeSet을 이용할 수 있다. 추가, 삭제, 조회 작업시 O(logn) 으로 수행된다. ) 근데 접근하기 편한 ArrayList 를 써서 풀었다. 😎 Time Complexity push - O(1) pop - O(n) //비효율적 peek - O(1) empty - …
댓글을 사용할 수 없습니다.