给定一个整数数组,求数组中出现次数超过数组长度一半的元素。 要求:时间复杂度为O(n)
arr: 非空整数数组
数组中出现次数超过数组长度一半的元素
arr=[1,2,2,3,2]
2
import java.util.*; public class Main { public int solution(int[] arr,int n) { int x = 0, votes = 0; for(int num : arr){ if(votes == 0) x = num; votes += num == x ? 1 : -1; } return x; } }