数组中出现次数超过一半的数

来源:互联网 发布:阿里实时数据 编辑:程序博客网 时间:2024/05/29 09:28
package com.google.android;public class FindBeyondHalfID {public static void main(String[] args) throws Exception {int[] data = { 1, 2, 2, 3, 4, 5, 2, 2, 2 };int result = find(data);System.out.println(result);}/** * 查出数组中出现次数超过一半的数 * @param data * @return * @throws Exception */private static int find(int[] data) throws Exception {if (data != null && data.length > 0) {int result = data[0];int times = 1;for (int i = 0; i < data.length; i++) {if (times == 0) {result = data[i];times = 1;} else if (data[i] == result) {times++;} else {times--;}}return result;} else {throw new Exception("data is null");}}}

0 0
原创粉丝点击