题目要求:对于一个已经顺序数组,删除重复的元素,并且返回新数组的长度
这题的特殊性在于,不允许创建新的数组来作为结果数组返回,并且原来数组超过结果长度的部分可以忽略

如果采用循环复制的方法 时间复杂度将达到O(n2) 在数据量大的场景下非常影响性能

下面方法的时间复杂度为O(n) 空间复杂度为O(1) 只需要遍历数组一次

/**
 * @author rale
 *
 *Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
 *Do not allocate extra space for another array, you must do this in place with constant memory.
 *For example,
 *Given input array nums = [1,1,2],
 *Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
 */
public class RemoveDuplicatesfromSortedArray {
    public int removeDuplicates(int[] nums) {
        if(nums.length<=0){
            return 0;
        }
        int index = 1;
        for(int i = 1 ; i<nums.length ; i++){
            if(nums[i]==nums[i-1]){
                continue;
            }
            nums[index] = nums[i];
            index++;
        }
        return index;
    }
}

第一次超过90% 特此记录!
clipboard.png


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行