Only one loop, and less code
import java.util.Map; import java.util.HashMap; 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; } }
- import java.util.Map;
import java.util.function.Function;import java.util.stream.Collectors;import java.util.stream.IntStream;- import java.util.HashMap;
/**I'm not sure how IntStream.sorted() performs time/space-wise,complexity noted here ignores whatever implementation is used to sort.Time Complexity : O(N)Space Complexity : O(1)*/- class MaxOccurence {
- public static int findMax(int[] nums) {
return nums == null || nums.length == 0 ? -1 : IntStream.concat(IntStream.of(nums).sorted(), IntStream.of(-1)).collect(() -> new int[]{-1, -1, -1, -1},//{current,highest,curr-count,highest-count}(arr, i) -> {if (arr[0] != i) {if (arr[2] > arr[3]) {arr[1] = arr[0];arr[3] = arr[2];}arr[2] = 0;arr[0] = i;}++arr[2];}, null)[1];}- 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;
- }
- }