FakeStandard

Posted on

Search Insert Position

#35.Search Insert Position

Problem statement

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

Explanation

็ตฆๅฎไธๅๆๅบ้ฃๅๅไธๅ็ฎๆจๅผ๏ผๅถไธญ้ฃๅๅง็ๅ็ด ไธ้่ค๏ผๅฆๆๅจ้ฃๅไธญๆพๅฐ็ฎๆจๅผๅ่ฟๅๅถ็ดขๅผ๏ผ่ฅ้ฃๅๅงไธๅญๅจ็ฎๆจๅผ๏ผๅ่ฟๅๆ็ถๆๅฅไฝ็ฝฎ็็ดขๅผ

้ๅถ่งฃๆณ็ๆ้่ค้ๅบฆ็บ O(log n)

Solution

็ฑ้ก็ฎ็ตฆ็ๆฏๅทฒๆๅบ้ฃๅ๏ผๆฒๆๅคชๅคๆณๆณ๏ผ็ดๆฅไฝฟ็จไบๅๆๅฐๆณไพ่งฃ

public int SearchInsert(int[] nums, int target)
{
int left = 0, right = nums.Length - 1, mid;

while (left <= right)
{
mid = (left + right) / 2;

if (nums[mid] == target) return mid;
else if (target > nums[mid]) left = mid + 1;
else right = mid - 1;
}

return left;
}

Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article ๐ท ๐ป ๐ผ

If you like it, please don't hesitate to click heart button โค๏ธ
or click like on my Leetcode solution