hahn

[LeetCode - C] 35. Search Insert Position 본문

코딩테스트 연습/LeetCode(C - Easy)

[LeetCode - C] 35. Search Insert Position

hahn 2022. 4. 6. 09:05
728x90
반응형
 

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);
}

 

728x90
반응형