java - 如何仅使用基本循环删除 int 数组的重复项
问题描述
该代码需要删除数组中的所有重复整数,但要保持简单。如果没有 system.arraycopy 或任何复杂的东西,就不能使用 set 或任何“超出”知识循环的东西。它是一个接收数字数组的构造函数,应该检查数字是否重复并创建一个没有重复的数组
例如:
{1,2,5,5,2,4,5,1} 将是 {1,2,5,4} 所以它应该创建一个数字大小不重复的数组。
试图创建一个循环来计算数字是否重复本身,只有如果不是,它才会添加它,但这不是最好的主意,因为它不会计算至少重复一次的数字
int repeat = 0;enter code here
int counter = 0;
if(se.length < 2)
{
System.out.println("Array smaller than 2, please change the size!");
return;
}
for(int i = 0; i < se.length; i++)
{
for(int j = 0; j < se.length; j++)
if(se[i] == se[j])
{
repeat++;
}
if(repeat == 0)
counter++;
repeat = 0;
}
解决方案
您可以尝试以下方法:
public static void removedups(int se[]) {
int repeat = 0;
int counter = 0;
if(se.length < 2) {
System.out.println("Array smaller than 2, please change the size!");
return;
}
//Find out all the duplicates and replace with 0
boolean isZeroPresent = false;
int zeroindex = -1;
for(int i = 0; i < se.length; i++) {
for(int j = i + 1; j < se.length; j++) {
if(se[i] == se[j]) {
if(se[i] == 0 && !isZeroPresent) {
isZeroPresent = true;
zeroindex = i;
}
se[j] = 0;
}
}
}
//find the exact count of the array which does not contains duplicates
int customIndex = 0;
for(int i = 0; i < se.length; i++) {
System.out.println(se[i]);
if(isZeroPresent && zeroindex == i) {
customIndex++;
continue;
}
if(se[i] == 0) {
continue;
}
customIndex++;
}
//create new array which will hold all the unique values and return
int arr[] = new int[customIndex];
int j = 0;
for(int i = 0; i < customIndex; i++) {
if(se[i] == 0) {
if(zeroindex == i) {
arr[j] = se[i];
j++;
}
continue;
}
arr[j] = se[i];
j++;
}
System.out.println("-----------------");
printArr(arr);
}
public static void printArr(int arr[]) {
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
推荐阅读
- c - C - 数组放入变量时从同一元素返回不同的值
- python - 将 RGBA 字节数组转换为 cv2 图像(没有错误,cv2 永远挂起)
- c++ - 如何使用主要参数添加更多堆栈?
- php - PHP Decimal128 字符串格式化
- ios - 打印语句总是崩溃
- azure-devops - 如何从 Azure DevOps 在 Microsoft AppCenter 中运行 XCUITests
- javascript - 如何延迟请求数据?
- python - pandas 中的高效 STAR 选择
- python - “int”类型的参数是不可迭代的问题
- javascript - 使用 Google App Script 替换 Google Sheet 中的文本而不重新格式化值