Dare2Solve
The searchInsert
function finds the index at which a target value should be inserted into a sorted list nums
to maintain the order. If the target value is found in the list, the function returns the index of the target value.
To determine the correct position for the target value, we need to traverse the list and compare each element with the target. By checking where the target fits within the existing elements, we can either find its position or determine where it should be inserted.
Initialize Variables:
result
: Initialize to 0, this will store the index where the target should be inserted or found.Iterate Through the List:
result
to the next index (i + 1
) and break the loop.result
to the current index (i
) and break the loop.Return Result:
result
, which represents the correct index for the target value.O(n), where n is the number of elements in the list. We may need to traverse the entire list in the worst case.
O(1), as we only use a constant amount of extra space for the result
variable.
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int result = 0;
for (int i = nums.size() - 1; i >= 0; i--) {
if (target > nums[i]) {
result = i + 1;
break;
}
if (target == nums[i]) {
result = i;
break;
}
}
return result;
}
};
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
result = 0
for i in range(len(nums) - 1, -1, -1):
if target > nums[i]:
result = i + 1
break
if target == nums[i]:
result = i
break
return result
class Solution {
public int searchInsert(int[] nums, int target) {
int result = 0;
for (int i = nums.length - 1; i >= 0; i--) {
if (target > nums[i]) {
result = i + 1;
break;
}
if (target == nums[i]) {
result = i;
break;
}
}
return result;
}
}
var searchInsert = function(nums, target)
{
let result = 0;
for(let i=nums.length-1; i>=0; i--)
{
if(target>nums[i])
{
result = i+1;
break;
}
if(target==nums[i])
{
result = i;
break;
}
}
return result;
};