北京市建设工程信息网站,网站关键词设置技巧,网站开发什么叫前端后端,电脑做网站服务器需要什么软件数组中有一个数字出现的次数超过数组长度的一半#xff0c;请找出这个数字。 你可以假设数组是非空的#xff0c;并且给定的数组总是存在多数元素。 示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2
代码#xff1a;
class Solution { public int majorityElement(in…数组中有一个数字出现的次数超过数组长度的一半请找出这个数字。 你可以假设数组是非空的并且给定的数组总是存在多数元素。 示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2
代码
class Solution { public int majorityElement(int[] nums) { if(nums.length0) { return 0; } int result nums[0]; int count0; for(int i0;inums.length;i) { if(count0i!0) { result nums[i]; } if(nums[i]result) { count; } else { count--; } } return result; }
}