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
Constraints:
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums contains distinct values sorted in ascending order.
- -104 <= target <= 104
1.Python
거의 무조건반사로 튀어나오는 Binary Search 코드다.
그냥 무의식적으로 적었는데 맞다.. 코딩마져 암기식으로 해버리는 나 ㅠ
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
s = 0
e = len(nums)-1
while s<=e:
mid = s+(e-s)//2
if nums[mid] < target :
s = mid+1
elif nums[mid] > target :
e = mid-1
else : return mid
return s
2. C
이게 time complexity가 log N이 나오는 Binary Search의 정석이다.
int searchInsert(int* nums, int numsSize, int target) {
int l = 0;
int r = numsSize-1;
while(l<=r){
int mid = l + (r-l)/2 ;
if(nums[mid] > target){r=mid-1;}
else if(nums[mid] < target){l=mid+1;}
else return mid;
}
return l;
}
직과적으로 O(N)의 Search는 아래와 같지.
int searchInsert(int* nums, int numsSize, int target) {
for(int i=0;i<numsSize;i++){
if(nums[i]==target || nums[i]>target)
return i;
}
return numsSize;
}
3. C++
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int a = 0;
int b = nums.size()-1;
while(a<=b){
int m = a+(b-a)/2;
if(nums[m] > target) b=m-1;
else if(nums[m] < target) a=m+1;
else return m;
}return a;
}
};
이상, 쉬어가는 코너였습니다..ㅎ
'Coding_Practice' 카테고리의 다른 글
Length of Last Word[E,String] (0) | 2024.07.27 |
---|---|
Merge Sorted Array[E,Array,Two Pointers,Sorting] (0) | 2024.07.27 |
Convert 1D Array Into 2D Array[E,Array,Matrix,Simulation] (0) | 2024.07.26 |
Adding Spaces to a String[M,ArrayTwo Pointers,String,Simulation] (0) | 2024.07.26 |
Reverse Linked List[E,Linked List,Recursion] (0) | 2024.07.26 |