It is possible to exit before the end is reached, but in this example I added complexity to the model via the sorting.
import java.util.Arrays; class MaxOccurence { public static int findMax(int[] nums) { Arrays.sort(nums); int countNumberMax = -1; int numberMax = -1; int currentCount = 0; int currentNumber = nums.length>0?nums[0]:-1; for(int i = 0; i < nums.length; i++) { if(currentNumber == nums[i]) { currentCount++; if(countNumberMax < currentCount) { countNumberMax = currentCount; numberMax = currentNumber; } } else { currentCount = 1; currentNumber = nums[i]; } if(countNumberMax > nums.length/2 || countNumberMax > currentCount + nums.length - i) { break; } } return numberMax; } }
import java.util.Map;import java.util.HashMap;- import java.util.Arrays;
- class MaxOccurence {
- public static int findMax(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();int lastBigVal = -1;int lastBigValIndx = -1;for(int i=0;i<nums.length;i++){map.putIfAbsent(nums[i],0);if(map.containsKey(nums[i])) {map.put(nums[i], map.get(nums[i]) + 1);if(lastBigVal < map.get(nums[i])) {lastBigVal = map.get(nums[i]);lastBigValIndx = nums[i];}}}return lastBigValIndx;- Arrays.sort(nums);
- int countNumberMax = -1;
- int numberMax = -1;
- int currentCount = 0;
- int currentNumber = nums.length>0?nums[0]:-1;
- for(int i = 0; i < nums.length; i++)
- {
- if(currentNumber == nums[i])
- {
- currentCount++;
- if(countNumberMax < currentCount)
- {
- countNumberMax = currentCount;
- numberMax = currentNumber;
- }
- }
- else
- {
- currentCount = 1;
- currentNumber = nums[i];
- }
- if(countNumberMax > nums.length/2 || countNumberMax > currentCount + nums.length - i)
- {
- break;
- }
- }
- return numberMax;
- }
- }