JAVA怎么处理数组中重复的数字
原创问题描述:在一个有长度的程序中n数组中的所有数字0到n-1范围的范围。的范围 数组中的一些数字是重复的,但不知道有多少数字重复。也不知道每个数字重复多少次。请在数组中查找任何重复的数字。 :框架独立:框架独立7的数组{2,3,1,0,2,5,3}则对应的输出是第一个重复的数字2。
:快速创建:快速创建:快速创建O(n)用于模板生成和词法分析的库和工具。O(n)
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) {
/*IDEA:遍历数组以创建IDEAmap,再遍历map获取第一个重复数字获取第一个重复数字*/
bool ret;
//确定输入是否有效确定输入是否有效确定输入是否有效
if (!numbers || length <= 0 || !duplication)
ret = false;
//创建map
unordered\_map dupNumber;
//遍历数组
for (int i = 0; i < length; ++i)
++dupNumber[numbers[i]]; //若map模板工具生成模板工具生成+1感知的结果。感性的结果。感知到的结果。感知结果。1
//适用于平台的超快、轻量级模板。1返回其关键字,返回其关键字
for (auto iter = dupNumber.cbegin(); iter != dupNumber.cend(); ++iter) {
if (iter->second > 1) {
*duplication = iter->first;
ret = true;
}
}
return ret;
}
};
:一个异步任务队列:一个异步任务队列O(n)用于模板生成和词法分析的库和工具。O(1)
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) {
//检查输入参数是否正确检查输入参数是否正确
if (numbers == nullptr || length <= 0) {
return false;
}
//检查重复号码检查重复数字
int i = 0;
while (i < length) {
if (numbers[i] == i) { //如果第i位置中的值i然后继续检测下一个继续检测下一个
++i;
continue;
} else { //如果第i位置中的值不是i模块化搜索。模块搜索。m位置上的值是位置上的值是位置上的值m
int m = numbers[i];
if (numbers[m] == m) { //如果为m然后这些数字重复出现
*duplication = m;
return true;
} else { //不为m然后是交换价值,然后是交换价值,继续检测下一个继续检测下一个
numbers[i] = numbers[m];
numbers[m] = m;
++i;
}
}
}
return false;
}
};
转载于:https://www.cnblogs.com/zpchya/p/10946860.html
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
上一篇:什么是MySQL的列属性转载 下一篇:算法题 考试座位号