leetcode解题之26、80 # Remove Duplicates from Sorted Array Java版

本文探讨了LeetCode中的26题和80题,涉及如何在有序数组中移除重复元素。在原地操作数组,不使用额外空间,详细解释了解题思路和代码实现,包括两种不同情况:重复元素最多出现两次的情况。
摘要由CSDN通过智能技术生成

26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being1 and 2 respectively. It doesn't matter what you leave beyond the new length.

注意考虑清楚为啥循环else先pre++??

最后为啥返回pre+1???

	public int removeDuplicates(int[] A) {
		if (A.length <= 1)
			return A.length;

		int prev = 0; // point to previous
		int curr = 1; // point to current

		while (curr < A.length) {
			if (A[curr] == A[prev]) {
				curr++;
			} else {
				prev++;
				A[prev] = A[curr];
				curr++;
			}
		}

		return prev + 1;
	}

改进版

	public int removeDuplicates(int[] nums) {
		if (nums == null || nums.length == 0)
			return 0;
		int i = 0;
		for (int n : nums) {
			// i<1代表第一个元素,
			// 当n>nums[i-1]代表不等,可以赋值,并且i++
			if (i < 1 || n > nums[i - 1])
				nums[i++] = n;
		}
		return i;

	}

80. Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":

What if duplicates are allowed at most twice?
Given sorted array nums = [1,1,1,2,2,3],

For example,

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

同上一题的方法一

	public int removeDuplicates(int[] A) {
		if (A.length <= 2)
			return A.length;

		int prev = 1; // point to previous
		int curr = 2; // point to current

		while (curr < A.length) {
			if (A[curr] == A[prev] 
					&& A[curr] == A[prev - 1]) {
				curr++;
			} else {
				prev++;
				A[prev] = A[curr];
				curr++;
			}
		}

		return prev + 1;
	}

同上一题的方法二

	public int removeDuplicates(int[] nums) {
		if (nums == null || nums.length == 0)
			return 0;
		int i = 0;
		for (int n : nums) {
			//
			//不同点
			if (i < 2 || n > nums[i - 2])
				nums[i++] = n;
		}
		return i;
	}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值