题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路:
1.使用sort函数排序,统计中间的数字出现的次数,超过一半,即为输出。
2.如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。
在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。
代码:
//1.sort排序
import java.util.Arrays;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Arrays.sort(array);
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]==array[array.length/2]){
count++;
}
}
if(count>array.length/2){
return array[array.length/2];
}else{
return 0;
}
}
}
//2.数组遍历
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length == 0){
return 0;
}
int count=1;
int p = array[0];
for(int i = 1 ; i< array.length ; i++){
if(count == 0){
p = array[i];
count = 1;
}else if(p == array[i]){
count++;
}else{
count--;
}
}
count = 0;
for(int i = 0 ; i< array.length; i++){
if(p == array[i]){
count++;
}
}
return (count*2 > array.length) ? p : 0;
}
}
京公网安备 11010502036488号