每天一道剑指offer-数组中出现次数超过一半的数字
- 2019 年 10 月 4 日
- 笔记
前言
今天的题目 每天的题目见github(看最新的日期): https://github.com/gzc426 具体的题目可以去牛客网对应专题去找。
昨天的题解
题目
每天一道剑指offer-数组中出现次数超过一半的数字 来源: https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目详述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
题目详解
思路
- 使用一个计数count = 1,当前数num,每当数组中数和当前数num相同,那么count就加1,不相同就减一,因为是找出现的数超过数组的长度的一半,所以最后如果有出现的数超过数组长度一半的,count肯定是大于0的数
代码
public class Solution { public int MoreThanHalfNum_Solution(int [] array) { if(array.length == 0) return 0; int count = 1; int number = array[0]; for(int i=1;i<array.length;i++) { if(array[i] == number) {//如果与number相等,那么count++,可能是超过一半的那个数 count++; }else{ count--;//如果与number不相等,count就减一 if(count == 0) {//如果count等于0了,说明这个数在这里出现次数已经被抵消了 count = 1;//重新记录count为1 number = array[i];//number记录当前这个数 } } } if(count > 0) {//如果count大于0说明有可能存在这样的数,是出现次数大于数组的一半的 //还有一种可能是最后刚好一个数连续出现了2次,导致count>0 count = 0; for(int i=0;i<array.length;i++) {//去遍历数组,计数这个number到底出现了几次 if(number == array[i]) count++; } if(count > array.length/2) return number;//出现超过一半 } return 0; } }
代码截图(避免乱码)
