169.多数元素
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
思路1:
通解:遍历数组,统计不同元素个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.wereash.scut_hot100;
import java.util.HashMap; import java.util.Scanner;
public class Solution169 { public static void main(String[] args){ Scanner scanner=new Scanner(System.in); String[] str=scanner.nextLine().split(","); int n=str.length; int[] nums=new int[n]; for (int i=0;i<n;i++){ nums[i]=Integer.parseInt(str[i]); } HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); int max=0; int maxAns=0; for(int i=0;i<n;i++){ int count=0; if(!map.containsKey(nums[i])){ map.put(nums[i],1); }else{ count=map.get(nums[i]); count++; map.put(nums[i],count); } if(max<count){ max=count; maxAns=nums[i]; } } if(max>n/2) { System.out.println("多数元素为:"+maxAns); }else { System.out.println("不存在多数元素!"); } } }
|
思路2:
特解:摩尔投票,相同元素统计,不同元素相消;因为大于n/2,所以一定有能活到最后的元素
1 2 3 4 5 6 7 8 9 10 11 12 13
| int vote=0; int candidate=0; for(int i=0;i<n;i++){ if(vote==0){ candidate=nums[i]; } if(candidate==nums[i]){ vote++; }else { vote--; } } System.out.println("多数元素为:"+candidate);
|