This problem is actually written in Java, but it should still be readable by anyone who has never worked with Java. The problem is as follows:
Say that a "clump" in an array is a series of 2 or more adjacent elements of the same value. Return the number of clumps in the given array.
countClumps({1, 2, 2, 3, 4, 4}) → 2
countClumps({1, 1, 2, 1, 1}) → 2
countClumps({1, 1, 1, 1, 1}) → 1
My solution is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
public int countClumps(int[] nums) {
int count = 0;
if(nums.length == 0) return count;
int currentNum = nums[0];
boolean counted = false;
for(int i = 1; i < nums.length; ++i){
if(nums[i] == currentNum && !counted){ count++; counted = true; }
else{ currentNum = nums[i]; counted = false; }
}
return count;
}
|
This solution works for every case except where the elements of nums are ubiquitous (i.e. {1,1,1,1,1,1}) In which case it returns 2. I have searched through my code time and time again and I cannot find the cause. Please help!
EDIT: Please tell me the issue with my code rather than giving me a new solution.