Remove duplicates from integer array

前端 未结 23 2386
执念已碎
执念已碎 2020-12-01 18:52

I having a problem with coding this:

Write a static method named removeDuplicates that takes as input an array of integers and returns as a result a new

23条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 19:27

    This is an interview question. Question : Remove Duplicates from an array in place :

    public class Solution4 {
        public static void main(String[] args) {
    
               int[] a = {1,1,2,3,4,5,6,6,7,8};
    
              int countwithoutDuplicates =  lengthofarraywithoutDuplicates(a);
              for(int i = 0 ; i < countwithoutDuplicates ; i++) {
                  System.out.println(a[i] + " ");
              }
        }
    
        private static int lengthofarraywithoutDuplicates(int[] a) {
            int countwithoutDuplicates = 1 ;
            for (int i = 1; i < a.length; i++) {
                  if( a[i] != a[i-1]      ) {
                     a[countwithoutDuplicates++] = a[i]; 
                  }//if
            }//for
            System.out.println("length of array withpout duplicates = >" + countwithoutDuplicates);
            return countwithoutDuplicates;
    
        }//lengthofarraywithoutDuplicates
    
    
    }
    

    In Python :

    def lengthwithoutduplicates(nums):
        if not nums: return 0
        if len(nums) == 1:return 1
        # moving backwards from last element i.e.len(a) -1 to first element 0 and step is -1
        for i in range(len(nums)-1,0,-1):
          # delete the repeated element
            if nums[i] == nums[i-1]: del nums[i]
            # store the new length of the array without the duplicates in a variable
            # and return the variable
        l = len(a)      
        return l
    
    
    
    a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8];
    
    l = lengthwithoutduplicates(a)
    for i in range(1,l):print(i)
    

    In Python: list comprehension using enumerate

    a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8]
    
    aa = [ ch  for i, ch in enumerate(a) if ch not in a[:i] ]
    print(aa) # output => [1, 2, 3, 4, 5, 6, 7, 8]
    

提交回复
热议问题