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

后端 未结 10 793
逝去的感伤
逝去的感伤 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:04

    this is the finest solution to remove duplicate element without apply sorting and collections.

    public static int[] removeElm(int arr[]) {
        int[] tempArr = new int[arr.length];
        int j = 0;
        tempArr[j] = arr[0];
        for (int i = 1; i < arr.length; i++) {
            boolean check = false;
            for (int k = 0; k < j + 1; k++) {
                if (tempArr[k] != arr[i]) {
                    check = true;
                } else {
                    check = false;
                    break;
                }
            }
            if (check) {
                tempArr[++j] = arr[i];
            }
        }
        return tempArr;
    }
    

提交回复
热议问题