题目:数组中出现次数超过一半的数
要求:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路一:
如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。
在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。
1 public class Solution { 2 public int MoreThanHalfNum_Solution(int [] array) { 3 //考虑特殊情况 4 if(array.length == 0) return 0; 5 if(array.length == 1) return array[0]; 6 //采取同时消去两个不同的数字,直到剩下最后一个数字,有可能是正确的结果 7 int num = array[0]; 8 int count = 1; 9 for(int i=1;i<array.length;i++){ 10 if(num==array[i]) count++; 11 else count--; 12 if(count==0){ 13 num=array[i]; 14 count=1; 15 } 16 } 17 //最后进行判断 18 count=0; 19 for(int j=0;j<array.length;j++){ 20 if(array[j]==num) count++; 21 } 22 if(count*2 > array.length) return num; 23 else return 0; 24 } 25 }
注意:当数组是123的时候,count=1,而j数字3不是正确结果,所以需要验证
第一个循环只能求出出现次数最多的元素,不能保证这个元素出现的次数大于数组长度的一半,所以要进行验证
思路二:
先排序,然后最中间的那个数字肯定是结果. 排序复杂度至少是N Olog(N). 对于思路一:复杂度是 O(N) +O(N) ,所以选择思路一会更好一些
本地编译器代码
1 import java.util.*; 2 public class Solution612Day1 { 3 public static int MoreThanHalfNum_Solution(int [] array) { 4 if(array.length == 0) return 0; 5 if(array.length == 1) return array[0]; 6 int num = array[0]; 7 int count = 1; 8 for(int i=1;i<array.length;i++){ 9 if(num==array[i]) count++; 10 else count--; 11 if(count==0){ 12 num=array[i]; 13 count=1; 14 } 15 } 16 count=0; 17 for(int j=0;j<array.length;j++){ 18 if(array[j]==num) count++; 19 } 20 if(count*2 > array.length) return num; 21 else return 0; 22 } 23 public static void main(String [] args) { 24 Scanner sc = new Scanner(System.in); 25 System.out.println("请输入数组的长度"); 26 int len = sc.nextInt(); 27 System.out.println("请依次输入数组中的元素"); 28 int[] array = new int[len]; 29 for(int i=0;i<len;i++) { 30 array[i] = sc.nextInt(); 31 } 32 sc.close(); 33 int result = MoreThanHalfNum_Solution(array); 34 System.out.println("该数组中出现次数超过一半的数字为" + result); 35 36 } 37 } 38 39 40 41 42