LeetCode题解——删除排序数组中的重复项


我的LeetCode代码集:https://github.com/cnamep001/LeetCode

原题链接:https://leetcode-cn.com/problems/trapping-rain-water/description/




题目描述:

img

知识点:数组、双指针

思路:一个指针从前往后遍历数组,另一个指针记录非重复元素的值

非重复元素的数量一定小于或等于数组总长度

这是一个排序数组,我们判断该元素是否重复只需要判断该元素是否与其前一个元素相同即可。如果重复,我们不记录该数字。否则,我们记录该数字。

整个过程中,我们只遍历了一遍数组,时间复杂度是O(n),其中n为nums数组的长度。空间复杂度是O(1),因为我们是在原数组中修改值,并没有使用额外的空间。



实现代码:

package com.m.remove_duplicates_from_sorted_array.solution1;


public class Solution1 {
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return 0;
        }
        int index = 1;
        for (int i = 1; i < n; i++) {
            if (nums[i] == nums[i - 1]) {
                continue;
            }
            nums[index] = nums[i];
            index++;
        }
        return index;
    }
}



LeetCode解题报告: