数组中的奇数

时间:2018-05-14 05:39:05

标签: data-structures

您将获得一个包含N个整数的数组A.你必须回答Q查询。

查询格式如下:

L R

在这里你必须得到所有数字的总和 ,对于那些在子阵列L到R中具有奇数频率的那些 第一行输入包含单个整数N,下一行包含N个空格分隔的整数,数组A的元素。下一行输入包含单个整数Q.Q行跟随每个包含两个空格分隔的整数L和R. 样本输入

5 1 2 2 2 1 3 1 3 1 4 1 5

示例输出

1 7 6

解释

对于查询1:1的频率为1,而2的频率为2,所以答案为1

对于查询2:1具有频率2和2具有频率3所以,答案是7 - - - - - - - - - - - - - - -解 - - - - - - - - - - -------------------

{{

公共课三星测试 {

public static void main(String[] args) 
{


    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] arr = new int[n];
    for (int i = 0; i < n; i++) {
        arr[i] = sc.nextInt();
    }

    int q = sc.nextInt();
    for (int i = 0; i < q; i++) {
        int l = sc.nextInt();
        int r = sc.nextInt();
        findOddSum(arr, l, r);
    }
}

private static long findOddSum(int[] arr, int l, int r) 
{
    long sum = 0;
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = l-1; i < r; i++ ) {
        if( map.get(arr[i]) == null ) {
            map.put(arr[i], 1);
        } else {
            int freq = map.get(arr[i]);
            map.put(arr[i], freq+1);
        }
    }

    Set<Integer> freqset = map.keySet();
    for (int val:freqset) 
    {
        int freq = map.get(val);
        if (freq%2 != 0) {
            sum = sum+freq*val;
        }
    }       
    System.out.println(sum);
    return sum;     
}

} }}

上面的解决方案是不对的(如HackerEarth)。请为我建议一个有效的解决方案。

1 个答案:

答案 0 :(得分:0)

你有任何解决方案,因为我的解决方案在隐藏的测试用例中也失败了。

包RD;

import java.util.HashMap; import java.util.Scanner;

公共课OddSum {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int[] arr=new int[n];

    for(int i=0;i<n;i++)
    {
        arr[i]=sc.nextInt();
    }

    int query=sc.nextInt();
    while(query>0)
    {
        HashMap<Integer, Integer> hs=new HashMap<>();
        int left=sc.nextInt();
        int right=sc.nextInt();
        for(int i=left-1;i<right;i++)
        {
            if(!hs.containsKey(arr[i]))
            {
            hs.put(arr[i],1);
            }
            else
            {
                hs.put(arr[i],hs.get(arr[i])+1);
            }
        }
        int sum=0;
        for(Integer value:hs.keySet())
        {
            if(hs.get(value)%2!=0)
            {
                sum=sum+hs.get(value)*value;
            }
        }
        System.out.println(sum);
        query--;
    }
}

}

相关问题