数据结构算法题/删除数组中重复元素

题目
  给定一个排序的数组,将数组中的重复元素去掉,相同的只保留一个,并且返回数组新的元素个数,
不要创建一个新的数组来保存结果。在常量时间内解决这个问题 

解题思路
  从第二个元素开始处理,记为当前处理的元素,如果当前元素与他的前一个元素相同就删除这个元素,
如果不同就将它移动到正确的位置,返回最后数组元素个数。比如输入的数组为{1,2,3,3,4,5,5,6},
则最后的数组为{1,2,3,4,5,6}共6个元素。
也就是index和next位置对于的元素不等的时候next往后走,相等的时候赋值并同时往后走。

public class RemoveArrDua {
    public int removeDuplicates(int[] A) {
        if (A.length == 0) {
            return 0;
        }

        int index = 0;//[0,index]记录去重之后的数组下标
        int next = 1;

        // 算法思想:找index之后的比A[index]大的数,如是找到就移动到A[index+1]处,
        // index移动到下一个位置,next移动到下一个位置,再找比A[index]大的数

        while (next < A.length) {
            while (next < A.length && A[index] == A[next] ) { //找不等于A[index]的元素
                next++;
            }

            if (next < A.length) {//也就是遇到了后面不相同元素,需要index指针往后移
                //遇到第一个不相等的元素就交换
                index++;
                A[index] = A[next];
                next++;
            }
        }
        return index;
    }

    private void swap(int[] a, int x, int y) {
        int tmp = a[x];
        a[x] = a[y];
        a[y] = tmp;
    }

    public static void main(String[] args) {
        RemoveArrDua removeArrDua = new RemoveArrDua();
        int[] dataArr = {1,2,3,3,4,5,5,6};
        int newLength = removeArrDua.removeDuplicates(dataArr);
        for (int i = 0; i <= newLength; i++) {
            System.out.println(dataArr[i]);
        }
    }
}

https://blog.csdn.net/DERRANTCM/article/details/47034985

猜你喜欢

转载自blog.csdn.net/fkyyly/article/details/83901766