Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should ru ...
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
代码如下:(方法一:超内存)
1 public class Solution { 2 public List<Integer> majorityElement(int[] nums) { 3 List<Integer> list=new ArrayList<>(); 4 if(nums.length==0) 5 return list; 6 Arrays.sort(nums); 7 int[] a=new int[nums[nums.length-1]+1]; 8 9 for(int i=0;i<nums.length;i++)10 a[nums[i]]++;11 12 for(int i=0;i<nums.length;)13 {14 if(a[nums[i]]>nums.length/3)15 {16 list.add(nums[i]);17 i=i+a[nums[i]]-1;18 }19 }20 21 22 return list;23 }24 }
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:229. Majority Element II
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。