简述 :
给定一个数组,找出数组中元素出现次数超过数组长度一半的元素
如数组:
[4, 3, 2, 1, 1, 1, 1, 1, 1, 0 ]
其中超过一半的元素就是 1
两种实现的 算法描述:
1) 用快排中的Partition,分割数组直到找到pos等于数组正当中的那个元素,返回那个索引的值
2) 可以考虑成,结果的那个值对抗不等于结果的那个值,两方面打擂台,最后谁还留在台上,谁就是最后的解
代码:
package offer;
/**
* In one array, there may be one element, its occurrence is more
* than half of the array size, so use these two methods to get
* the OccurrenceMoreThanHalf number
*/
public class OccurrenceMoreThanHalf {
public static void main(String[] args) {
int array[] = new int[10];
for(Integer i = 0; i < 5; i++)
array[i] = 4 - i;
for(Integer i = 0; i < 5; i++)
array[i + 4] = 1;
System.out.print("Raw Array Data: [");
for(Integer i : array){
System.out.print(i + ", ");
}
System.out.println("]");
System.out.println("Get Number Through Method_1: "
+ getNumMethod_1(array));
System.out.println("Get Number Through Method_2: "
+ getNumMethod_2(array));
}
public static int getNumMethod_1(int array[]){
int middle = array.length >> 1;
int start = 0;
int end = array.length - 1;
int pos = Partition(array, start, end);
while(pos != middle){
if(pos < middle){
start = pos + 1;
pos = Partition(array, start, end);
}
else{
end = pos - 1;
pos = Partition(array, start, end);
}
}
return array[pos];
}
public static int Partition(int array[], int start, int end){
int baseValue = array[start];
int basePos = start;
for(int i = start + 1; i <= end; i++){
if(array[i] < baseValue){
basePos++;
Swap(array, i , basePos);
}
}
Swap(array, start, basePos);
return basePos;
}
public static void Swap(int array[], int pos1, int pos2){
int temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
}
public static int getNumMethod_2(int array[]){
if(array.length == 0)
throw new IllegalArgumentException();
int resultNum = array[0];
int occurrence = 0;
for(int i = 0; i < array.length; i++){
if(array[i] == resultNum)
occurrence++;
else{
if(--occurrence == 0)
resultNum = array[i];
}
}
return resultNum;
}
}
输出: