Remove duplicate elements from sorted array

Topic description:
Remove duplicate elements in an array such as 1,2,2,3,3,4,5,6,6->1,4,5

Realize the idea:
Simply put. If the current element is the first element, just compare it to the next element for equality, if not, add it directly to the new array.
If the current element is not the first element, compare its adjacent left and right elements for equality, if not, add it.
The details are:
first find a benchmark, if it is the first element, define a cursor, point to the second element, then traverse the array, compare the benchmark with the element pointed to by the cursor, if they are equal, move the cursor one bit, if not If they are equal, modify the benchmark to the value of the current cursor, and then compare whether the next bit of the cursor is equal to the benchmark. If they are equal, continue to move the cursor. If they are not equal, add the benchmark to a new array. However, it will miss the case where an element is not a repeated element, so an element needs to be treated specially.

public class GetOffer3 {
    public static void main(String[] args) {
        int arr[] = { 1, 2, 2, 3, 3, 4, 5, 6, 6,8,9,10,10 };
        List temp = remove(arr);
        for (int i = 0; i < temp.size(); i++) {
            System.out.print(temp.get(i) + ",");
        }
    }

    private static List remove(int[] arr) {
        if (arr.length == 1) {
            return Arrays.asList(arr);
        }
        int tem =arr[0];
        int i=1;
        List list = new ArrayList();
        if(tem!=arr[i]){
            list.add(tem);
        }
        while(i<arr.length){
            if(tem==arr[i]){
                ++i;
            }else{
                tem=arr[i];
                if(tem!=arr[i+1]){
                    list.add(tem);
                }else{
                    ++i;
                }
            }
        }
        return list;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326280859&siteId=291194637