/ /配列内の重複する要素を特定する方法-Java、配列

配列内の重複要素を特定する方法は? - java、配列

forループ中に配列の要素を互いに比較しようとしています。私の場合、何らかの理由で削除できなかった重複値がいくつかありますが、それらを判断する必要があります。

ここに私が持っているものがあり、それは私のために働いていません

int x;
int table[] = {1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9, 10};

for (x = 0; x <= table.length; x++) {
if (x == 0 || x + 1 < table.length) { //determine that element is not last
if (table[x] == table[x + 1]) { //determine if next element is the same
System.out.println(table[x] + "if x = x + 1");
}

//determine that element is equal to previous but not equal to next
if (table[x] != table[x + 1] && table[x] == table[x - 1]) {
System.out.println(table[x] + " if x != x + 1 but x = x - 1");
} else {
System.out.println(table[x]);
}
}

if (x + 1 == table.length) { //determine that element is last
System.out.println(table[x]);
}
}

回答:

回答№1は0

コードに多くのエラーがありますが、

int x;
int table[] ={1,2,2,3,4,5,5,6,7,8,9,9,10};

for (x = 0; x < table.length; x++){ // <-- NOT <=
if (x + 1 < table.length){ //<-- what if the table only has one element?
if (table[x] == table[x + 1]) { // <-- Add a {, Java is hard to read without
//                            braces.
System.out.println(table[x] + "if x = x + 1");
} else if (x > 0 && table[x] == table[x - 1]) { // <-- check that x is
// greater then 0 before subtracting 1
System.out.println(table[x] + " if x != x + 1 but x = x - 1");
} else {
System.out.println(table[x]);
}
if (x + 1 == table.length){ //determine that element is last
System.out.println(table[x]);
}
}
}

回答№2の場合は0

JDKでこれを行うには多くの方法があります。代わりにCollectionsクラスを使用すると、このタスクをはるかに簡単に実行できます。たとえば、次の手順を実行できます。

  1. 配列をListオブジェクト(ArrayListなど)に変換します
  2. 次に、新しいSetインスタンス(HashSet for例)コンストラクター引数として最初のステップのリストを提供します。セットには一意の整数のみが含まれるので、それだけで作業を続けることができます。重複を見つけたい場合は、次の手順に従ってください。
  3. 残念ながら、「removeAll」は使用できません重複を取得するメソッド。おそらく、ステップ2でセットに対してforループを作成し、ステップ1のリストでremoveメソッドを呼び出す必要があります。「remove」メソッドは最初の出現のみを削除するため、ちょうどリストを作成する必要があります。複製。

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

また、「guavaまたはapache commonsコレクションへの依存関係を追加する場合は、それぞれにこの問題の解決に役立つ可能性のある適切なMultimap実装があります。


回答№3の場合は0

そのためにHasmMapを使用できます。 [1、2、2、3、4、5、1、8、4]などの配列がある場合
それはあなたにマップを与えます:{[1->(0,6)]、[2->(1,2)]、[3->(3)]、[4->(4、8)]、 [5->(5)]、[8->(7)]}

// mapping from number to indexes in the array where duplicates of number exists
HashMap<Integer, List<Integer>> duplicates = new HashMap<Integer, List<Integer>>();
for(int i=0; i < table.length; i++) {
int current = table[i];
List<Integer> dubList = duplicates.get(current);
if(dubList == null) {
dubList = new ArrayList();
duplicates.put(i, dubList);
}
dubList.add(current);
}

回答№4の場合は0

あなたは次のコードを試すことができます

HashSet hs = new HashSet();
int table[] ={1,2,2,3,4,5,5,6,7,8,9,9,10};
for (int x = 0; x < table.length; x++)
{
hs.add(table[x]);
}
System.out.println(hs);
List<Integer> array = new ArrayList<Integer>(hs);
System.out.println(array);

今、あなたはアイデアを得ることができます...