java - 从排序数组中删除重复项,以便允许两个重复项
问题描述
问题:给定一个排序数组 nums,就地删除重复项,使重复项最多出现两次并返回新长度。
不要为另一个数组分配额外的空间,您必须通过使用 O(1) 额外内存就地修改输入数组来做到这一点。
我的解决方案:无论如何,这个代码总是在一个索引上丢失。有人可以帮我为什么吗?例如,我的示例输入应该返回 6,但它返回 5。
int[] arr2= {1,1,1,2,3,4,4};
int i=findDupsMedium(arr2);
System.out.println(i);
static int findDupsMedium(int[] arr) {
int index=0;
if(arr.length>1) {
for(int i=0;i<2;i++) {
arr[index++]=arr[i];
}
}
//System.out.println("index:" + index);
for(int ii=2;ii<arr.length;ii++ ) {
int diff=ii-2;
if(arr[ii] != arr[diff]) {
arr[index++]=arr[ii];
}
}
return index;
}
解决方案
为此,您需要跟踪length
数组的变化以及何时更新主循环的index
.
boolean
标志还用于跟踪一系列重复发生的时间。
public static int findDupsMedium(int[] arr2) {
int size = arr2.length;
boolean foundFirstDuplicate = false;
for (int i = 0; i < arr2.length - 1; i++) {
for (int k = i + 1; k < size;) {
if (arr2[i] == arr2[k]) {
if (foundFirstDuplicate) {
// If we're here, this must be third
// duplicate in a row so copy up the array
// overwriting the third dupe.
for (int g = k; g < arr2.length - 1; g++) {
arr2[g] = arr2[g + 1];
}
i--; // and readjust outer loop to stay in
// position
// and effective size of array is one smaller
// so adjust that
size--;
}
// set first time a duplicate is found and keep this set
// until no more duplicates
foundFirstDuplicate = true;
break;
}
// no third or more duplicate so set to false
foundFirstDuplicate = false;
break;
}
}
return size;
}
要验证它是否正常,请添加以下方法
static void display(int[] a, int size) {
int[] t = Arrays.copyOf(a, size);
System.out.println(Arrays.toString(t));
}
并调用方法如下:
int[] arr2 = { 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5
};
int size = findDupsMedium(arr2);
display(arr2, size);
推荐阅读
- javascript - 如何修复此 Angular 组件中的 2 个错误?
- excel - If 语句 if Row 未概述
- ios - 在 ios 中使用无服务器的 Twilio 语音通话?
- ios - SwiftUI 工具栏主要文本字段失去了对文本编辑的关注
- java - 使用用户语音唤醒并启动应用程序
- python - Plotly,表达:使用自定义数据通过点击事件获取国家名称?
- excel - 将 Excel 工作表转换为 PDF,无限循环错误
- python - 无法使用 Selenium(Python)按类名按元素定位
- android - 如何在 Android 中比较和合并两个 JSON 键
- haskell - Haskell中通过索引访问的语法糖,惰性和列表元素之间的关系是什么?