java - 如何在重复数组中保持零值?
问题描述
我仍在努力为此代码获取正确的输入,我需要删除重复项并返回结果。在此之前,我一切正常:
给定数组
[100, 0, 3, 4, 4, 562, 100]
答案应该是
[100, 0, 3, 4, 562]
但我得到的是
[100, 3, 4, 562]
(所以它删除了 0)
有什么办法可以添加到我的代码中,因为我不允许使用任何内置函数、ArrayList、List、Set 等,所以只需实现我自己的解决方案和函数。
public static int[] removeDuplicates(int[] input) {
int[] withoutDubs = new int[input.length];
int pos = 0;
for(Integer element: input) {
if(!checkIfInArray(withoutDubs, element)) {
withoutDubs[pos] = element;
pos++;
}
}
int[] result = new int[pos];
for(int i = 0; i < pos; i++) {
result[i] = withoutDubs[i];
}
return result;
}
public static boolean checkIfInArray(int[] input, int number) {
if(input == null) {
return false;
}
for(Integer num: input) {
if(num == number) {
return true;
}
}
return false;
}
解决方案
withoutDubs
第一次实例化时默认填充0。
因此即使在数组中只出现一次也checkIfInArray(withoutDubs, 0)
返回。true
0
您可以将索引传递给checkIfInArray
,以便它不会搜索所有withoutDubs
数组。它应该只检查索引0
到pos - 1
.
public static boolean checkIfInArray(int[] input, int last, int number) {
if(input == null) {
return false;
}
for(int i = 0; i < last; i++) {
if(input[i] == number) {
return true;
}
}
return false;
}
并将方法调用从
checkIfInArray(withoutDubs, element)
到
checkIfInArray(withoutDubs, pos, element)
推荐阅读
- javascript - 如何过滤js中的对象数组?
- java - 关于 java.lang.NoClassDefFoundError: quickfix/MessageStoreFactory 的问题
- robotframework - 带有 RIDE 的循环机器人框架
- c# - 验证 EWS 应用程序 - 下一步是什么
- assembly - 如何从此加密创建解密
- sql - 匹配 h2/postgres 中的文字百分比?
- c# - 如何按名称路由net core mvc
- ibm-mobilefirst - MobileFirst:在 React Native 中处理二进制响应
- docker - Docker 容器退出代码 132
- typo3 - 如何获取用于后端模块的控制器的 flexform 值?