I am now learning C++, and started with tasks in LeetCode. The task is binarySearch. Got an issue with return statement when target found. Here is my solution:
class Solution {
public:
int search(vector<int>& nums, int target) {
int mid = nums.size() / 2;
while (mid < nums.size() && mid >= 0) {
cout << mid << ' ' << nums[mid] << endl; //for debuging
if (nums[mid] == target) {
cout << "WTF"; //PRINTS
return mid; // Doesn't work!
}
else if (target > nums[mid]) {
mid += mid / 2;
}
else if (target < nums[mid]) {
mid -= mid / 2;
}
}
return -1;
}
};
The problem is with return mid;
. The output on test case [-1,0,3,5,9,12], target=9 is
Time Limit Exceeded
2 5
3 9
WTF3 5
2 3
1 0
1 0
1 0
1 0...
So, if statement works, but function continues working after return command. I've tried to compile same code with g++ and everything works nice.
Your function implementation is wrong. For example when the vector nums
contains only one element then the variable mid
will not be changed
else if (target > nums[mid]) {
mid += mid / 2;
}
else if (target < nums[mid]) {
mid -= mid / 2;
}
because the expression mid / 2
is equal to 0
. As a result you will have an infinite loop.
The function can be implemented the following way
class Solution {
public:
std::vector<int>::size_type search( const std::vector<int> &nums, int target )
{
std::vector<int>::size_type low = 0, high = nums.size();
while ( low != high )
{
auto mid = low + ( high - low ) / 2;
if ( target < nums[mid] )
{
high = mid;
}
else if ( nums[mid] < target )
{
low = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
};