Saturday, February 25, 2012

This is to remove dups from a sorted int or char[]



 public class RemoveDups {  
      public static void removeDups(int[] a){  
           if(a == null || a.length < 2){  
                return;  
           }  
           int count = 1; //init to 1 to take care of last matching character  
           for(int i = 1; i < a.length; i++){  
                if(a[i-1] == a[i]){  
                     count++;  
                     if(count > a.length/2){  
                          System.out.println("The val "+a[i]);  
                          return;  
                     }  
                }else{  
                     count = 1;  
                }  
           }  
      }  
      public static void removeDupsStr(String str){  
           if(str == null || str.length() < 2){  
                return;  
           }  
           char a[] = str.toCharArray();  
           int src = 1;  
           int dst = 1;  
           while(src < a.length){  
                if(a[src-1] == a[src]){  
                     src++;  
                }else{  
                     a[dst] = a[src];  
                     dst++;  
                }  
           }  
           System.out.println("The str is "+new String(a,0,dst));  
      }  
      public static void removeDupsStringInN(String str){  
           if(str == null || str.length() < 2){  
                return;  
           }  
           char[] a= str.toCharArray();  
           boolean[] flag = new boolean[256];  
           for(int i = 0; i < flag.length; i++){  
                flag[i] = false;  
           }  
           int src = 0;  
           int dst = 0;  
           while(src < a.length){  
                if(!flag[a[src]]){  
                     a[dst] = a[src];  
                     dst++;  
                     flag[a[src]] = true;  
                }  
                src++;  
           }  
           System.out.println("The str is "+new String(a,0,dst));  
      }  
      public static void main(String args[]){  
           int a[] = { 1,1,1,1,3,3,3,3,3};  
           removeDups(a);  
           removeDupsStr("aaijsy");  
           removeDupsStringInN("sayaji");  
      }  
 }  

No comments:

Post a Comment