《劍指Offer》java實現 數組中出現數字超過1半的數字



import java.util.ArrayList;

public class OccurenceMoreThanOneHalf {

 public static void main(String[] args) {
  int a[]={1,2,2,2,2,3,5,4,2,2};
  getoccurencymorethanonehalf(a); 
 }
 
 //判斷數組中是否存在出現次數超過長度1半的元素
 public static boolean checkmorethanonehalf(int a[],int b){
  int count=0;
  for(int i=0;i<a.length;i++){
   if(a[i]==b){
    count++;
   }
  }
  if(count*2>a.length){
   return true;
  }else{
   return false;
  }
 }
 
 public static void getoccurencymorethanonehalf(int [] a){
  if(a.length==0){
   return;
  }else{
   ArrayList<Integer> a1=new ArrayList<Integer>();
   int index=1;
   int temp=a[0];
   a1.add(temp);
   for(int i=1;i<a.length;i++){
    if(a[i]!=temp){
     index--;
     if(index==0){
      temp=a[i];
      index=1;
      a1.add(temp);
     }
    }else{
     index++;
    }    
   }
   int result=a1.get(a1.size()-1);
   if(checkmorethanonehalf(a, result)){
    System.out.println(result);
   }else{
    System.out.println("輸入不符合要求");
   }   
  }    
 }
 
 public static void exch(int a[],int i,int j){
  int temp=a[i];
  a[i]=a[j];
  a[j]=temp;
 }
 
 public static int partition(int a[],int start,int end){
  int basevalue=a[start];
  int basepos=start;
  for(int i=start+1;i<=end;i++){
   if(a[i]<basevalue){
    exch(a, i, basepos);
   }
  }
  exch(a, start, basepos);
  return basepos;
 }
 
 public static void getoccurencymorethanonehalf2(int a[]){
  int mid=a.length/2;
  int start=0;
  int end=a.length-1;
  int pos=partition(a, start, end);
  while(pos!=mid){
   if(pos< mid){
    start=pos+1;
    pos=partition(a, start, end);
   }else{
    end=pos-1;
    pos=partition(a, start, end);
   }
  }
  if(checkmorethanonehalf(a, a[pos])){
   System.out.println(a[pos]);
  }else{
   System.out.println("輸入數組不符合要求");
  }
  
  //return a[pos];
 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章