题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
牛客链接:
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&&tqId=11181&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
解题思路:
有多种解法,目前提供两种
第一种暴力解决,两层循环得到出现次数最多的数字和次数,然后判断次数是否大于长度的一半
第二种如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。
代码一:
暴力解决,时间复杂度为o(n*n)
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int len = numbers.size();
if(len == 0) {
return 0;
}
int count = 0;
int max = 0;
int number;
for(int i=0; i<len; i++) {
count = 0;
for(int j=i+1; j<len; j++) {
if(numbers[i] == numbers[j]) {
count++;
}
}
if(count >= max) {
max = count;
number = numbers[i];
}
}
if (max+1 > len/2) {
return number;
}
return 0;
}
};
代码二:
利用次数规律来解决,时间复杂度o(n)
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int len = numbers.size();
if(len == 0) return 0;
int result = numbers[0];
int times = 1;
for(int i=1; i<len; i++) {
if(times == 0) {
result = numbers[i];
times = 1;
} else if (result == numbers[i]) {
times++;
}else {
times--;
}
}
times = 0;
for(int i=0; i<len; i++) {
if(result == numbers[i]) {
times++;
}
}
if(times > len/2) {
return result;
}
return 0;
}
};
注意:
题目规律