Leetcode日常刷码(2)解决数组去重问题(Java)

Java解决有序数组去重:LeetCode算法题解析
本文探讨了如何在LeetCode中解决有序数组去重的问题,强调了数组必须有序这一前提。通过两种方法进行解答,包括使用数组下标和中间变量,以及利用快慢指针。尽管在不考虑时间复杂度和空间复杂度的情况下问题简单,但题目要求O(n)时间和O(1)空间,因此双指针成为常见解法。

问题描述:(切记!!!给出的数组必须有序)

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

问题解决思路:

有两种解决办法

1,利用数组下标和中间变量解决

2,利用快慢指针解决

具体内容请看代码注释

代码实现:

package Algorithm;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

public class Example2 {
	//利用数组下标和临时变量处理数组问题
	public static int GainArreylength1(int[] array){
		if (array == null || array.length == 0){
			return 0;
		}
		if (array.length == 1){
			return 1;
		}
		else{
			int temp = array[0];//一般情况将临时变量设置为数组的第一个元素
			int len = 1;
			for (int i = 1; i < array.length; i++){
				if (temp == array[i]){//如果后面的元素和temp相等,那就一直往后找
					continue;
				}
				else {//如果遇到不相等的,立即更新temp,并给计数器len+1
					temp = array[i];
					array[len] = array[i];//这是为了最后返回去掉重复数字后的数组
					len ++;
				}
			}
			return len;
		}
		
	}
	//利用快慢指针来处理去除重复问题(其中有一个问题,快慢指针的方法在无时无刻的改变
	//数组array的值,所以如果要返回去重后的数组,不太容易)
	public static int GainArreylength2(int[] array ){
		if (array.length == 0){
			System.out.print("数组为空");
		}
		int i = 0;//i为慢指针
		for (int j = 1; j < array.length; j++ ){//j为快指针
			if (array[j] != array[i] ){//当快慢指针不相等时
				i++;//移动慢指针
				array[i] = array[j];//将快指针所指向的数组值赋给慢指针所指向的数组
			}
			
		}
		return i+1;
			
	}
	public static void main(String[] args) {
		int[] num = {0,0,1,1,3,3,5,5,6};
		System.out.print(GainArreylength1(num));
		
	}

}

总结:这道题如果不要求,O(n)的时间复杂度, O(1)的空间复杂度的话,会很简单。 但是这道题是要求的,这种题的思路一般都是采用双指针

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值