Point 1 has already been covered, so I'm responding to point 2. First the code in question:
vector<int> twoSum(vector<int>& nums, int target)
{
static int MAX = 99999;
static int DELT = 49999;
vector<int> ans;
int x[MAX];
memset(x, 0, sizeof(x));
for (int i = 0; i < nums.size(); i++)
{
if (x[nums[i] + DELT])
{
ans.push_back(((i + 1) < x[nums[i] + DELT] ?
(i + 1) : x[nums[i] + DELT]));
ans.push_back(((i + 1) > x[nums[i] + DELT] ?
(i + 1) : x[nums[i] + DELT]));
return ans;
}
x[target - nums[i] + DELT] = i + 1;
}
}
Note that the only return
statement in the function is nested inside a for
loop and an if
statement. This allows for the possibility that the return
statement never reached because the loop was not entered entered or if (x[nums[i] + DELT])
was never be true. One easy way to trigger this behaviour is to input an empty nums
vector:
for (int i = 0; i < 0; i++)
Will never enter the loop and never reach the return statement. What will be returned in this case? No one knows, and it may be different with every run. Maybe the program will crash. Maybe it will plop down on your sofa an watch an Adam Sandler movie marathon while drinking rum and vodka.
"Oh, but this will never happen!" you say. Maybe it won't, but optimism is a poor choice when set against rigorously tested and enforced requirements. Regardless the compiler is pointing out a hole in the logic that could result in much pain and debugging, and this is a hole that can easily be filled
vector<int> twoSum(vector<int>& nums, int target)
{
static int MAX = 99999;
static int DELT = 49999;
vector<int> ans;
int x[MAX];
memset(x, 0, sizeof(x));
for (int i = 0; i < nums.size(); i++)
{
if (x[nums[i] + DELT])
{
ans.push_back(((i + 1) < x[nums[i] + DELT] ?
(i + 1) : x[nums[i] + DELT]));
ans.push_back(((i + 1) > x[nums[i] + DELT] ?
(i + 1) : x[nums[i] + DELT]));
break;
}
x[target - nums[i] + DELT] = i + 1;
}
return ans;
}
Now return ans
is always reached, but this allows for the possibility that the returned ans
contains no or incorrectly processed information. Not a good answer as twoSum
may no longer kill your program, but processing its output could.
bool twoSum(vector<int>& nums, int target, vector<int> &ans)
{
static int MAX = 99999;
static int DELT = 49999;
int x[MAX];
memset(x, 0, sizeof(x));
for (int i = 0; i < nums.size(); i++)
{
if (x[nums[i] + DELT])
{
ans.push_back(((i + 1) < x[nums[i] + DELT] ?
(i + 1) : x[nums[i] + DELT]));
ans.push_back(((i + 1) > x[nums[i] + DELT] ?
(i + 1) : x[nums[i] + DELT]));
return true;
}
x[target - nums[i] + DELT] = i + 1;
}
return false;
}
twoSum
returns true
only if the exit condition was reached. If it returns false
the contents of ans
cannot be trusted. More work on the algorithm is required to ensure that ans
is always complete and correct or twoSum
needs to be wrapped in another function that validates the inputs before executing.