Remove Duplicates from Sorted Array LeetCode

本文介绍了一种在原地且使用常数级额外空间去除已排序数组中重复元素的方法。通过一个示例,展示了如何使每个元素只出现一次,并返回新数组的长度。代码实现了去除重复项的功能,并保留了原有数组的顺序。

描述
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
分析

代码 

 1 public class solution {
 2 
 3     public static void main(String[] args) {
 4         
 5         int[] A= {1,1,1,2,2,3};
 6         int n = A.length;
 7         int index=removeDuplicates(A,n);
 8         int[] B=new int[index];//定义好数组长度不好改
 9         for(int i=0;i<index;i++) {
10             B[i]=A[i];
11             System.out.println(B[i]);
12         }
13 
14     }
15         public static int removeDuplicates1(int A[],int n) {
16         if(n==0) return 0;
17         int index=0;
18         for(int i=1;i<n;i++) {
19             if(A[index]!=A[i])
20                 A[++index]=A[i];
21         }
22         return index+1;   //返新的长度
23     }
24 }

 

转载于:https://www.cnblogs.com/ncznx/p/9167232.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值