[英]removing the duplicates from array
我在 Java 中有关于 arrays 的作业,我被困在这个问题上。
填写下面的程序主体,这会从排序后的数组输入中删除重复值。 您的解决方案应将变量结果设置为删除重复值后剩余的值数。 例如,如果输入为
(0,1,1,2,3,3,3,4,4)
,则输入删除重复项后的前五个值应为(0,1,2,3,4)
,结果的值应该是5。
这是我的代码:
import java.util.Scanner;
public class RemoveDups {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int[] input = 0,1,1,2,3,3,3,4,4;
int result;
int count = input[0];
result++;
String count1="";
int result2=0;
count1=count1+count;
input[0]=Integer.parseInt(count1);
count1="";
for (int j = 1; j <input.length-1;j++ ) {
if (count != input[j+1] && result2 == 0||count != input[j-1] &&result2==0 ) {
input[j] = count;
result++;
count = input[j + 1];
count1=count1+count;
input[j]=Integer.parseInt(count1);
count1="";
}
}
for (int i = 0; i < result; i++) {
System.out.println(input[i]);
}
}
}
}
我不能做这个练习。 我总是留下数组中与所有其他单元格不同的最后一个单元格,并且此代码对我不起作用。
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int j = 0;
for (int i=0; i < n-1; i++){
if (arr[i] != arr[i+1]){
arr[j++] = arr[i];
}
}
arr[j++] = arr[n-1];
return j;
}
public static void main(String args []) {
int arr[] = {0,1,1,2,3,3,3,4,4};
int length = arr.length;
length = removeDuplicateElements(arr, length);
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
答案将是 0 1 2 3 4
请参考以下链接。 使用单独的索引删除数组中的重复元素
我不确定您是需要过滤数组还是只需要结果值。 下面将为您提供结果值。 由于这是家庭作业,我建议您使用以下逻辑来创建非重复数组。
int result = 1;
if(input == null || input.length == 0){
result = 0;
}
else{
for(int i = 1; i < input.length; i++){
if(input[i-1] != input[i]){
result++;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.