given an array with positive and negative numbers find the first continuous subarray that sums to 0
bool FindFirstPair(int& nStart, int& nEnd, int a[], int n)
{
nStart = nEnd = n;
int nCount = 0;
hash_map<int, int> hash;
bool bSet = false;
for (int i = 0; i < n; i++)
{
nCount += a[i];
if (0 == nCount)
{
nStart = 0;
nEnd = i;
return true;
}
if (hash.find(nCount) == hash.end())
hash[nCount] = i;
else
{
int nIndex = hash[nCount];
if (nIndex+1 < nStart || (nIndex+1 == nStart && i - nIndex - 1 < nEnd - nStart))
{
nStart = nIndex+1;
nEnd = i;
bSet = true;
}
}
}
return bSet;
}
有思路并不意味着做对,面试官看重 1,思路是否灵活;2,思维是否严谨