《剑指offer》数组中出现次数超过一半的数字

xiaoxiao2021-02-28  63

题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。 解析一:简单思维,时间复杂度为O(n2)。直接先去重,然后对每个数做记数,超过一半就输出。

import java.util.*; public class Solution { public int MoreThanHalfNum_Solution(int [] array) { List<Integer> list= new ArrayList<>(); for(int i:array){ list.add(i); } Set<Integer> set = new LinkedHashSet<>(list);//1 2 3 4 5 int half =array.length/2; for(Integer i: set){ int count=0; for(int j=0;j<array.length;j++){ if(i==array[j]){ count++; } } if(count>half){ return i; } } return 0; } }

解析二:直接先排序,然后一次搜索就可以完成任务。时间负责度为O(n)就可以完成任务

//排序前:1,2,3,2,2,2,5,4,2 //排序后:1,2,2,2,2,2,3,4,5 import java.util.*; public class Solution { public int MoreThanHalfNum_Solution(int [] array) { Arrays.sort(array);//首先排序 if(array.length==1||array.length==2){ return array[0]; } int count=1; int half=array.length/2; for (int i=2;i<array.length;i++){//从第3个数开始判断 if(array[i]==array[i-1]){//和前一个数一样就记数 count++; if(count>half){//检查要是大于一半就返回 return array[i]; } continue; }else {//与前面数不一样,目前新出现一次了 count=1; } } return 0;//说明没有满足条件的,直接返回 } }
转载请注明原文地址: https://www.6miu.com/read-80815.html

最新回复(0)