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.