I am not sure why the value doesn't increase in my code when the code already exists. Any hint is really appreciated:
import java.util.HashMap;
public class MajorityElement {
public int majorityElement(int[] nums) {
int halfSize = nums.length/2;
int temp=0;
int majorityValue=0;
HashMap<Integer, Integer> valuesMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (valuesMap.containsValue(nums[i])) {
temp=valuesMap.get(nums[i]);
valuesMap.put(nums[i], temp++);
} else {
valuesMap.put(nums[i], 1);
}
}
for (Integer key : valuesMap.keySet()){
if (valuesMap.get(key)>= halfSize){
majorityValue=key;
}
}
return majorityValue;
}
public static void main(String[] argc){
MajorityElement majority=new MajorityElement();
int[] sampleArray={1,4,6,8,8,9,8,8,0,8};
int majorityRes=majority.majorityElement(sampleArray);
System.out.println("majority value is = [" + majorityRes + "]");
return;
}
}
UPDATE: I changed my code to
for (int i = 0; i < nums.length; i++) {
if (valuesMap.containsValue(nums[i])) {
// temp=valuesMap.get(nums[i]);
valuesMap.put(nums[i], valuesMap.get(nums[i])+1);
} else {
valuesMap.put(nums[i], 1);
}
}
and still it prints 0 for majorityRes
. Any idea why is that?
UPDATE': Fixed the problem by changing to containsKey()
which was a typo.
Your problem is on this line:
valuesMap.put(nums[i], temp++);
When ++ is placed directly after the variable name, Java executes the command and then increments the variable by one. So, this line uses the original value of "temp" to execute the command and then it increments by one.
What you want to do is increment the variable "temp" by one and then executing the command. In order to do this you need to put the ++ before the variable name like this:
valuesMap.put(nums[i], ++temp);
That way Java knows to increment the variable by one and then execute the rest of the command.