How can I remove duplicate elements from a given array in java without using collections

后端 未结 10 876
逝去的感伤
逝去的感伤 2021-01-06 02:20

I have an array elements like this:

int arr[] = {1,1,2,2,3,3,4,4};

I want to remove the duplicate elements from. Searched on the internet

10条回答
  •  误落风尘
    2021-01-06 03:01

    public static int[] removeDuplicates(int[] input){
    
        int j = 0;
        int i = 1;
        //return if the array length is less than 2
        if(input.length < 2){
            return input;
        }
        while(i < input.length){
            if(input[i] == input[j]){
                i++;
            }else{
                input[++j] = input[i++];
            }   
        }
        int[] output = new int[j+1];
        for(int k=0; k

    Source : http://java2novice.com/java-interview-programs/remove-duplicates-sorted-array/

提交回复
热议问题