描述
一个整型数组里除了两个数字只出现一次,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
数据范围:数组长度 2\le n \le 10002≤n≤1000,数组中每个数的大小 0 < val \le 10000000<val≤1000000
要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
提示:输出时按非降序排列。
分析:
这一题和51题的求解方式大同小异。都是统计字符出现的次数。需要判断出现次数为一次的字符。添加到一个数组里排序后输出。
一, 统计字符出现的次数
const temp = {};
const result = [];
array.forEach((item, index) => {
if (temp[item] !== undefined) {
temp[item] = (temp[item] + 1);
} else {
temp[item] = 1;
}
})
二,判断出现一次的字符
Object.keys(temp).forEach(key => {
if(temp[key] == 1) {
result.push(key);
}
});
三,排序后返回结果
return result.sort((a, b) => a - b);
完整代码
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
function FindNumsAppearOnce( array ) {
// write code here
const temp = {};
const result = [];
array.forEach((item, index) => {
if (temp[item] !== undefined) {
temp[item] = (temp[item] + 1);
} else {
temp[item] = 1;
}
})
Object.keys(temp).forEach(key => {
if(temp[key] == 1) {
result.push(key);
}
});
return result.sort((a, b) => a - b);
}
module.exports = {
FindNumsAppearOnce : FindNumsAppearOnce
};