Dare2Solve
Given an array of integers nums
and an integer target
, return the index of the target if it exists in the array. If it does not exist, return -1
. The search should be performed using a linear search algorithm.
The problem requires us to find a target element in a list of integers. A straightforward approach to solve this is by using linear search, where we iterate through each element in the array and compare it with the target. If we find a match, we return the index; if we complete the iteration without finding a match, we return -1
.
left
and right
, to represent the start and end of the array, respectively.left
pointer.left
).left
pointer.-1
.O(n), where n is the number of elements in the array. In the worst case, we may have to check all elements.
O(1), as no additional space is required other than a few integer variables.
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (right >= left) {
if (nums[left] == target) {
return left;
}
left++;
}
return -1;
}
};
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while right >= left:
if nums[left] == target:
return left
left += 1
return -1
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (right >= left) {
if (nums[left] == target) {
return left;
}
left++;
}
return -1;
}
}
var search = function (nums, target) {
var right = nums.length - 1
var left = 0;
while (right >= left) {
if (nums[left] === target) {
return left
}
left++
}
return -1
};