数组中出现次数超过一半的数字
题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。你可以假设数组是非空的,并且给定的数组总是存在多数元素。1<=数组长度<=50000
思路:
代码:
1. 开辟一个额外空间存储每个值出现的次数,时间复杂度最大为O(n),逻辑简单
1 function MoreThanHalfNum_Solution(numbers) 2 { 3 // write code here 4 if(numbers && numbers.length > 0){ 5 var length = numbers.length; 6 var temp = {}; 7 for(var i = 0; i < length; i++){ 8 if(temp['s'+numbers[i]]){ 9 temp['s'+numbers[i]]++; 10 }else{ 11 temp['s' + numbers[i]] = 1; 12 } 13 if(temp['s'+ numbers[i]] > length / 2){ 14 return numbers[i]; 15 } 16 } 17 return 0; 18 } 19 } 20 module.exports = { 21 MoreThanHalfNum_Solution : MoreThanHalfNum_Solution 22 };
2. 目标值的个数比其他所有值加起来的数多 记录两个变量 1.数组中的某个值 2.次数
1.当前遍历值和上一次遍历值相等?次数+1 : 次数-1。
2.次数变为0后保存新的值。
3.遍历结束后保存的值,判断其是否复合条件
事件复杂度O(n) 不需要开辟额外空间 , 逻辑稍微复杂。
1 function MoreThanHalfNum_Solution(numbers) 2 { 3 // write code here 4 if (numbers && numbers.length > 0) { 5 var target = numbers[0]; 6 var count = 1; 7 for (var i = 1; i < numbers.length; i++) { 8 if (numbers[i] === target) { 9 count++; 10 } else { 11 count--; 12 } 13 if (count === 0) { 14 target = numbers[i]; 15 count = 1; 16 } 17 } 18 count = 0; 19 for (var i = 0; i < numbers.length; i++) { 20 if (numbers[i] === target) count++; 21 } 22 return count > numbers.length / 2 ? target : 0; 23 } 24 } 25 module.exports = { 26 MoreThanHalfNum_Solution : MoreThanHalfNum_Solution 27 };

浙公网安备 33010602011771号