Code/LeetCode

[LeetCode] 35. Search Insert Position (Easy/Python)

코방코 2022. 9. 3. 17:52
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

Above is the link to the problem.

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.

Write an algorithm with O(log n) runtime complexity.

 

For example,

Input: nums = [1,3,5,6], target = 5
Output: 2
Input: nums = [1,3,5,6], target = 2
Output: 1

 

I solved this problem by writing the code below.

 

 

If the target doesn't exist in nums, then append the target and resort nums.

If the target exists in nums, no process is necessary.

Finally, return the index number of the target.

 

This code gets the top 8.62% of time efficiency and the top 17.24% of space efficiency.

 

728x90
반응형