分享一道面试常问的JAVA的简单算法题目,例题:
查找一个int数组中出现次数大于数组长度1/2的元素,下面是代码演示:
public static void main(String[] args) {
int[] nums={2,3,3,3,1 };
System.out.println(majorityElement(nums));
}
public static int majorityElement(int[] nums) {
Map<Integer, Integer> map=new HashMap<Integer, Integer>();
int majority=(nums.length+1)/2;
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);
}
if (map.get(nums[i])>=majority) {
return nums[i];
}
}
return 0;
}
运行输出即可实现效果