| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 | 31 |
- LeetCode Remove Duplicates from Sorted List in c
- 문자열제곱
- 임의 정밀도 / 큰 수 연산
- 수학
- KMP알고리즘
- 스택
- Queue
- 큰 수 연산
- 실패함수
- 큐
- 정수론
- 프로그래머스
- 다이나믹 프로그래밍
- LeetCode 83 c언어
- 해시를 사용한 집합과 맵
- 자료 구조
- 별 찍기
- 사칙연산
- 재귀
- 이분 탐색
- 조합론
- 구현
- 정렬
- 시뮬레이션
- 연결리스트 중복제거
- LeetCode 83번
- 문자열
- 유클리드 호제법
- 브루트포스 알고리즘
- 연결리스트 정렬
- Today
- Total
hahn
[LeetCode - C] 35. Search Insert Position 본문
Search Insert Position - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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
Constraints:
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums contains distinct values sorted in ascending order.
- -104 <= target <= 104
Solution 1
You must write an algorithm with O(log n) runtime complexity.
이 항목 때문에 어떻게 풀지 고민하다가
이분 탐색 하면 될 거 같아서
전에 했던 나무 자르기 참고해서 해결했다.
단계별로 풀어보기(이분 탐색 - 나무 자르기)
2805번: 나무 자르기 (acmicpc.net) 2805번: 나무 자르기 첫째 줄에 나무의 수 N과 상근이가 집으로 가져가려고 하는 나무의 길이 M이 주어진다. (1 ≤ N ≤ 1,000,000, 1 ≤ M ≤ 2,000,000,000) 둘째 줄에는 나..
ahnstu.tistory.com
int searchInsert(int* nums, int numsSize, int target)
{
int max;
int mid;
int min;
max = numsSize;
min = 0;
if (nums[0] > target)
return (0);
if (nums[numsSize - 1] < target)
return (numsSize);
while (min <= max)
{
mid = (max + min) / 2;
if (nums[mid] < target)
min = mid + 1;
else
max = mid - 1;
}
return (min);
}
int searchInsert(int* nums, int numsSize, int target)
{
int max;
int mid;
int min;
max = numsSize - 1;
min = 0;
while (min <= max)
{
mid = (max + min) / 2;
if (nums[mid] == target)
return (mid);
else if (nums[mid] < target)
min = mid + 1;
else
max = mid - 1;
}
return (min);
}
'코딩테스트 연습 > LeetCode(C - Easy)' 카테고리의 다른 글
| [LeetCode - C] 58. Length of Last Word (0) | 2022.04.12 |
|---|---|
| [LeetCode - C] 53. Maximum Subarray (0) | 2022.04.12 |
| [LeetCode - C] 28. Implement strStr() (0) | 2022.03.30 |
| [LeetCode - C] 27. Remove Element (0) | 2022.03.25 |
| [LeetCode - C] 26. Remove Duplicates from Sorted Array (0) | 2022.03.25 |