2017-01-24 10 views
-1
public static int countRepeats(int[] items) { 
    int l=items.length; 
    int num=0; 
    int[] count=new int[l]; 
    for(int i=0;i<l;i++){ 
     for(int j=i+1;j<l;j++){ 
      if(items[i]==items[j]){ 
       count[i]++; 
      } 
     } 
    } 
    for(int i=0;i<l;i++){ 
     if(count[i]>0){ 
      num++; 
     } 
    } 
    return num; 
} 

// {1,2,1,3,4,5,5} 2を与えるべきである; 2numbersが // {0,0,0}を繰り返したが、私のコードはこの1つのために2を与える..数字が3回現れた場合、繰り返し数を数える際の繰り返し回数を避けるには?

+0

は、私が使用することができます?? –

答えて

1

コード{0, 0, 0}から、最初の要素は2としてカウントされ、2番目の要素は1としてカウントされ、最後の要素は0としてカウントされます。もちろん2です。これを試してください:

public static int countRepeats(int[] items) { 
    int num = 0; 
    Map<Integer, Integer> countMap = new HashMap<Integer, Integer>(); 
    for (Integer i : items) { 
     if (countMap.containsKey(i)) { // check if map does contain the key or not, if does, make this key'value +1; 
      countMap.put(i, countMap.get(i) + 1); 
     } else { // if not contain the key, just put it as a new key and the value is 1. 
      countMap.put(i, 1); 
     } 
    } 
    for (Integer item : countMap.values()) { 
     if (item > 1) { 
      num++; 
     } 
    } 
    return num; 
} 

Mapを使用して番号の表示時間を保存し、このマップのすべての値を取得し、1を超える値を数えれば、あなたが望むものを得ることができます。

+1

Java 8では、for(int i:items)countMap.merge(i、1、Integer :: sum);を実行できます。 – shmosel

1

アルゴリズムが正しくありません。あなたの入力についてはわかりませんが、すべての数値が正の値で、それほど大きくない(メモリを心配するほど大きくない)場合は、これを試してみてください。それは任意の数のリピートを処理できます。

public static int countRepeats(int[] items) { 
    int l=items.length; 
    int num=0; 
    int max=0; 
    for(int i=0;i<l;i++){ 
     if(items[i] > max) max = items[i]; // get the largest number 
    } 
    int[] count=new int[max + 1]; // assume count elements are initiated with 0 
    for(int i=0;i<l;i++){ 
     count[items[i]]++; 
    } 
    for(int i=0;i<=max;i++){ 
     if(count[i]>1){ 
      num++; 
     } 
    } 
    return num; 
} 
1

個別の項目のみを保存するように設定します。あなたは後者のセットのサイズを返し、その後、明らかにそれらを格納するために、重複して別のものを見つけるために、1セットを使用することができます。

public static int countRepeats(int[] items) { 
    Set<Integer> distinct = new HashSet<>(); 
    Set<Integer> duplicate = new HashSet<>(); 
    for (int item : items) { 
     if (!distinct.add(item)) { 
      // item was already contained in set 
      duplicate.add(item); 
     } 
    } 
    return duplicate.size(); 
} 
+0

これは今までのところ最良の答えです。 –

0

地図多分役立つ、ちょうど好き:whileループ

public static int countRepeats(int[] items) { 
     int res = 0; 
     Map<Integer,Integer> map = new HashMap<>(); 
     for(int i:items){ 
      map.put(i, map.get(i)==null?0:map.get(i)+1); 
     } 

     for(Integer key:map.keySet()){ 
      if(map.get(key)>0){ 
       res++; 
      } 
     } 
     return res; 
    } 
+1

これはForwardの回答とは何らかの形で違いますか? –

+0

私はちょうど彼の答えを見ていない: - D –

+0

私はフォワードの答えは、まったく同じものを全体的にはしても、より良いと思う。 '? '操作は私が読むのがちょっと面白いものです。しかし、 'HashMap'に関する限られた知識の中には、' containsKey() 'を呼ぶことがないために、より大きいデータセットのほうが速いかもしれないと私の報告しているものもあります。 (よく知っている人は誰でも私を訂正することができます)。 – Adrian

関連する問題