如何计算数组中具有相同值的对的数量?

时间:2019-04-17 18:42:29

标签: arrays

我想对整数数组中的对数进行计数,例如array = {1,1,1,1,2,2,4,4,4,4}有4对。 这是我的代码

public static int countpairs(int[] arry){
    int pairs=0;
    int a=0;
    for(int i=0;i<arry.length;i++){
        int count=1;

        if(a!=arry[i]) {   
        for(int j=0;j<arry.length;j++){

        if(arry.length==1){
            return 0;
        }
        if(arry[i]==arry[j]&&i!=j){
            a=arry[j];
            count=count+1;
        }
    }
    pairs= pairs+(int)count/2;
    return pairs;
}

1 个答案:

答案 0 :(得分:0)

Java代码:

public class Main {

        public static void main(String[] args) throws IOException {
            List<Integer> list = Arrays.asList(1, 1, 1, 1, 2, 2, 4, 4, 4);
            long pair = 0;
            Set<Integer> distinct = new HashSet<>(list);
            for (Integer s : distinct) {
                pair += Collections.frequency(list, s) / 2;
            }
            System.out.println(pair);
        }

    }

C ++代码:

#include <iostream>
#include <string>
#include <algorithm> 
using namespace std;
 int countOccurrences(int arr[], int n, int x) 
{ 
    int res = 0; 
    for (int i=0; i<n; i++) 
        if (x == arr[i]) 
          res++; 
    return res; 
}

int main()
{

    int arr[] = {1,1,1,1,2,2,4,4,4}; 
    int n = sizeof(arr)/sizeof(arr[0]); 

    sort(arr, arr + n); 
    int pair=0;

    // Traverse the sorted array 
    for (int i=0; i<n; i++) 
    { 

       while (i < n-1 && arr[i] == arr[i+1]) 
          i++; 


      pair+= countOccurrences(arr,n,arr[i])/2;
    }
    cout<<pair;
    return 0;

}