我的代码几乎完成了,但问题是返回大小,它应该返回删除重复元素后的大小。它不会输出正确的大小。
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
输入元素数:4
输入Num[0]:2的值
输入Num[1]:2的值
您用来查找重复元素的过程很好,但您实际上并没有更改数组中的元素,您只是打印重复的元素,最好的方法是将重复元素的值作为标志更改,然后在删除重复元素后查找数组的长度,这将很容易:
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
array[j]=-1;
System.out.println("duplicate value:"array[j]);
}
}
因此,移除重复元素后的数组长度为:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}
spop key 如果set是空或者key不存在返回nil
统计一个一维数组中的各个元素的个数,然后删除多出来的重复元素,并输出结果。 例如:[1,2,2,2,3,3,3,3,3]—>[1,2,3] 解决思路 将重复元素的列表中的重复元素进行统计,并将统计结果放在dictionary中,key为元素,value为该元素的个数 更新此步方法:上述步骤的功能,能够通过另外一个方法实现,即collections.Counter() 然后通过for获取key,得到
027. Remove Element[E] 问题 Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place wi
本文向大家介绍jQuery 添加元素和删除元素的方法,包括了jQuery 添加元素和删除元素的方法的使用技巧和注意事项,需要的朋友参考一下 添加新的 HTML 内容 我们将学习用于添加新内容的四个 jQuery 方法: append() - 在被选元素的结尾插入内容 prepend() - 在被选元素的开头插入内容 after() - 在被选元素之后插入内容 before() - 在被选元素之前插
问题内容: 我有一本字典存放在 现在,我不想包含重复的,我应该使用什么? 问题答案: 只需创建一个可以通过键获取唯一值的过滤器即可。这样的事情应该做(我根本没有测试过,所以我把这件事留给你,这只是给你一个主意): 注意:Array.indexOf()在IE8中不起作用 ,因此,如果支持IE8,则需要在indexOf()中存根,或者需要使用稍微不同的方法。 其他想法:如果已经在引用那些库,那么最好创
问题内容: 我有一个非常大的.xml文件,我正在尝试制作一个新的.xml文件,该文件只包含了该较大文件内容的一小部分。我想指定一个属性(在我的情况下为itemID),并为其指定一些特定的值,然后它将除去所有具有那些itemID及其子元素的元素。 我的大型.xml文件如下所示: 该文件大约有9万行,大约9兆字节。 注意如何有itemID,某些项目类型可以(但不总是)在其中包含更多项目,并且这些子项也