LeetCode026——删除排序数组中的重复项

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82378663

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/description/

题目描述:

知识点:数组、双指针

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

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

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

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

JAVA代码:

public class Solution {
	
	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解题报告:

扫描二维码关注公众号,回复: 3109259 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82378663