java - 如何创建一个返回包含另一个数组重复值的新数组的函数
问题描述
我正在尝试解决一个问题,即返回一个新的双精度数组,其中包含来自另一个双精度数组的重复值。我不能在这个问题中使用 HashSets 或 ArrayLists。我尝试使用一种首当其冲的方法来交换原始数组和我制作的新数组中的索引。但是,我没有得到预期的结果。我附上了我的代码截图和我得到的输出。如果此函数正确,示例结果包括: new double [ ] {11, 22, 33, 44, 55, 66, 77, 88} < --removeDuplicates(new double [ ] {11, 11, 11, 11, 22, 33, 44, 44, 44, 44, 44, 55, 55, 66, 77, 88, 88})在此处输入图片描述
解决方案
我在http://www.GeekersforGeeks.org阅读了您问题的解决方案。在这里,我包括了到目前为止我发现的内容。在下面的代码中,在 removeDuplicates 函数中,创建了一个临时双精度数组,用于在删除重复项后保存新数组。
这里使用的逻辑非常简单。首先,它检查给定的数组是没有元素还是只有一个元素,如果是,它只返回数组,因为没有重复。
然后它开始遍历元素,如果两个附近的元素不相等(意味着元素是否唯一),那么这些元素将存储在新的 temp[] 数组中。如果找到重复项,它们将被忽略并且不存储在 temp[] 数组中。
最后,它将给定数组的最后一个元素存储到 temp[] 数组中。
然后它使用 temp[] 数组修改原始数组并返回原始数组而不重复。
static int removeDuplicates(double arr[], int n)
{
// return the array itself, if it is empty or contains only one element
if (n==0 || n==1)
return n;
//creating a temporary array to hold new array data
double[] temp = new double[n];
// Start traversing elements
int j = 0;
for (int i=0; i<n-1; i++)
//checking for duplicates and store elements in
//temp[] array if not duplicated.
if (arr[i] != arr[i+1])
temp[j++] = arr[i];
// Store the last element as whether
// it is unique or repeated, it hasn't
// stored previously
temp[j++] = arr[n-1];
// Modify original array
for (int i=0; i<j; i++)
arr[i] = temp[i];
return j;
}
推荐阅读
- c++ - 在 CLion 中调试时程序收到分段错误
- python - 列表列表增长后的奇怪行为
- sql - SQL 查询案例 when then 在 where 子句中
- php - 奏鸣曲管理员上的自定义批处理操作
- matlab - 你如何解决“未定义的函数或变量'mamfis'”?
- snowflake-cloud-data-platform - 如何将列数据类型从 boolean 更改为 varchar(50)?
- css - Chrome 在两台电脑上计算 CSS 不同
- javascript - 将servelt中的字符串转换为json数据并将其传递给javascript:ajax
- android - React Native 应用程序在启动时崩溃 - Android
- python - 在数据框列中获取 NaN 而不是正确的值