// partition 算法 privatestaticintpartition(int[] data, int start, int end){ if (end < start) { thrownew RuntimeException("参数错误"); } int num = data[end]; int more = end + 1; int cur = start; while (cur < more) { if (data[cur] <= num) { cur++; } else { int number = data[cur]; data[cur] = data[--more]; data[more] = number; } } return cur - 1; }
publicstaticintfindMoreThanHalfNumber(int[] data){ int start = 0; int end = data.length - 1; int index = partition(data, start, end); // middle 代表是 n /2 的位置 int middle = start + (end - start) / 2; while (index != middle) { if (index < middle) { start = index + 1; index = partition(data, start, end); } else { end = index - 1; index = partition(data, start, end); } } return data[index]; }