首先 试着 用hashMap来做 习惯一下Map
public class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> hashMap = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(!hashMap.containsKey(nums[i])) hashMap.put(nums[i], 1);
else{
int value = hashMap.get(nums[i]);
value++;
hashMap.put(nums[i], value);
}
}
Set<Map.Entry<Integer, Integer>> entrySet = hashMap.entrySet();
int count = 0;
for(Map.Entry<Integer, Integer> entry : entrySet){
if(entry.getValue() > nums.length/2) return entry.getKey();
}
return 0;
}
}
可以简化一下:
public class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> hashMap = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(!hashMap.containsKey(nums[i])) hashMap.put(nums[i], 1);
else{
int value = hashMap.get(nums[i]);
value++;
hashMap.put(nums[i], value);
}
if(hashMap.get(nums[i]) > nums.length/2)return nums[i];
}
return 0;
}
}
效率太低,得用其他方法。
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
讨论区看到的 醉了 自己笨死了。。