if my input is arr[]= {5,3,3,3,3,5,5,2} ,my output must be 5 2=7 I tried but i am geting output as 10,I dont understand what mistake I made,please help me out with this
public static void main(String[] args) {
int arr[]= {5,3,3,3,3,5,5,2};
LinkedHashMap<Integer,Integer> map=new LinkedHashMap<Integer,Integer>();
for(int i=0;i<arr.length;i ) {
if(map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i]) 1);
}
map.put(arr[i], 1);
}
int sum=0;
for(Map.Entry<Integer,Integer> e:map.entrySet()) {
if(e.getValue()%2!=0) {
sum=sum e.getKey();
}
}
System.out.println(sum);
}
}```
CodePudding user response:
Missing else
if(map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i]) 1);
}
else
map.put(arr[i], 1);
That's why your elements are being initialized with frequency 1 each time instead of incrementing. So output is 5 3 2=10
CodePudding user response:
you are overiding the increment instead of :
if(map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i]) 1);
}
map.put(arr[i], 1);
do
if(map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i]) 1);
}
else map.put(arr[i], 1);