求数组中出现次数超过一半的数字

xiaoxiao2021-02-28  134

在一个数组中,某个数字出现的次数超过了数组元素总长度的一半,找出这个数字。

package com.threeTop.www; /** * 找出数组中超过一半的元素 * @author wjgs * */ public class MoreThanHalf { /** * O(n)时间复杂度解法 * @param array */ public static void find(int[]array) { int t=array[0]; int n=0; for(int i=0;i<array.length;i++) { if(array[i]==t) { n++; } else { n--; } if(n==0) { t=array[i]; n=1; } } System.out.println("这个元素为"+t); } public static void main(String []args) { int []array={0,1,2,1,2,1,1}; MoreThanHalf.find(array); } }

转载请注明原文地址: https://www.6miu.com/read-17381.html

最新回复(0)