LeetCode - remove-duplicates-from-sorted-array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/toward_south/article/details/89480229

题目:

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].

题意:

给定一个排序后的数组,删除重复项,使每个元素只出现一次,并返回新的长度。

不要为另一个数组分配额外的空间,您必须在使用常量内存的地方执行此操作。

例如,

给定输入数组A =[1,1,2],

函数应该返回length =2, A现在是[1,2]

解题思路:

使用一个count指针,和i指针,count指针用来统计有效数字的长度,i用来从前往后扫,然后跳过重复的元素。

Java代码: 时间复杂度O(n) ,空间O(1)

 public static int removeDuplicates(int[] A) {
		 
		 if(A.length <= 0 || A == null) {
			 return 0;
		 }
		 
		 int count = 0;
		 for(int i = 0 ; i < A.length; i++) {
			 if(A[count] != A[i]) {
				 A[++count] = A[i];
			 }
			
			 
		 }
		 for(int j = 0 ;j<count;j++) {
			 System.out.println(A[j]);
		 }
		 return count+1;	 
	 }

猜你喜欢

转载自blog.csdn.net/toward_south/article/details/89480229