Search Insert Position
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.
You must write an algorithm with O(log n)
runtime complexity.
Constraints
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
contains distinct values sorted in ascending order.-104 <= target <= 104
Solution
The problem Search Insert Position
can be solved by implementing a simple binary search algorithm.
Implementation
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *mergeTwoLists(ListNode *list1, ListNode *list2)
{
ListNode *head = new ListNode();
ListNode *cur = head;
while (list1 && list2)
{
if (list1->val < list2->val)
{
cur = cur->next = list1;
list1 = list1->next;
}
else
{
cur = cur->next = list2;
list2 = list2->next;
}
}
cur->next = list1 ? list1 : list2;
return head->next;
}
};