Remove Duplicate from Sorted Array

package com.company;

public class Algorithm {
    int[] duplicate(int[] ints) {
        if (ints.length < 2) {
            throw new RuntimeException("Invalid array");
        }
        int i = 0, j = 0;
        while (i < ints.length) {
            if (ints[i] == ints[j]) {
            } else {
                j++;
                ints[j] = ints[i];
            }
            i++;
        }
        int[] unique = new int[j + 1];
        for (int k = 0; k <= j; k++) {
            unique[k] = ints[k];
        }
        return unique;
    }
}
package com.company;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class AlgorithmTest {
    @Test
    void duplicate1() {
        Algorithm algorithm = new Algorithm();
        int[] duplicate = algorithm.duplicate(new int[]{1, 1, 2, 2, 3, 3});
        Assertions.assertArrayEquals(new int[]{1, 2, 3}, duplicate);
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

test {
    useJUnitPlatform()
}

 

follow us on