我这里采用的是HashMap写法,运用了一下forEach方法,挺好用的
class Solution {
int value = 0 ;
int key = 0 ;
public int majorityElement(int[] nums) {
int x = nums.length / 2 ;
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0 ; i < nums.length ; i ++){
if(map.containsKey(nums[i])){
map.put(nums[i],map.get(nums[i])+1);
}else{
map.put(nums[i],1);
}
}
map.forEach((K,V)->{
if(value < V){
key = K ;
value = V ;
}
});
return key;
}
}
这篇博客分享了一种使用HashMap和Java的forEach方法来解决LeetCode题目的编程技巧,强调了这种方法的高效与便捷。
2148

被折叠的 条评论
为什么被折叠?



