牛客堂常见面试题精讲(一)5

来源:互联网 发布:全民k歌网络异常 编辑:程序博客网 时间:2024/06/07 10:13

数组中哪个数出现次数大于一半?

package com.zhao.niuke;public class Problem_06_FindMajority {//数组中的哪个元素出现次数大于一半//int[] arr = { 1, 2, 3, 1, 1, 2, 1 };public static void printHalfMajor(int[] arr) {int cand = 0;//候选int times = 0;//当前无候选for (int i = 0; i != arr.length; i++) {if (times == 0) {cand = arr[i];//从数组中第一个开始遍历先取出来放到候选中times = 1;//times代表当前候选出现的次数} else if (arr[i] == cand) {times++;}else {times--;}}times = 0;for (int i = 0; i != arr.length; i++) {if (arr[i] == cand) {times++;}}//再次判断times是否大于一半if (times > arr.length / 2) {System.out.println(cand);} else {System.out.println("no such number.");}}public static void main(String[] args) {int[] arr = { 1, 2, 3, 1, 1, 2, 1 };printHalfMajor(arr);//数组中的哪个元素出现次数大于一半}/* * 数组中是否每个元素都只是出现一次? * 数组中哪个元素出现次数大于一半? */}
解析:根据debug一步步调试得到解决方案!也就是根据比较

0 0
原创粉丝点击