现有答案无法编译通过主要是因为每次交换后数组的次序改变,导致最终输出的可能不是第一次出现的
我的方法:用哈希表遍历同时判断map[numbers[i]],当其等于2时即可输出,如果无则返回false;
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
unordered_map<int,int> map;
for(int i=0;i<length;i++)
{
map[numbers[i]]++;
if(map[numbers[i]]>=2)
{
*duplication=numbers[i];
return true;
}
}
return false;
}
};


京公网安备 11010502036488号