Day13(多数元素)
class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> record = new HashMap<>();
int n = nums.length;
for(int i=0;i<n;i++){
if(!record.containsKey(nums[i])){
record.put(nums[i],1);
}else{
record.put(nums[i],record.get(nums[i])+1);
}
}
int maxValue = 0;
int ans = 0;
for(Map.Entry<Integer,Integer> entry:record.entrySet()){
if(entry.getValue()>maxValue){
maxValue = entry.getValue();
ans = entry.getKey();
}
}
return ans;
}
}
Map遍历的四种方式
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 2);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}
for (Integer key : map.keySet()) {
System.out.println("key = " + key);
}
for (Integer value : map.values()) {
System.out.println("key = " + value);
}
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> entry = it.next();
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}
map.forEach((key, value) -> {
System.out.println(key + ":" + value);
});
}