首页 > 代码库 > leetcode------Remove Duplicates from Sorted Array

leetcode------Remove Duplicates from Sorted Array

标题:Remove Duplicates from Sorted Array
通过率:31.9%
难度简单

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

前边我做过一个类似的题目。但是那个是用链表实现的,这个题让我头疼的是数组中的元素无法删除,题目又要求不让用额外空间,那绝壁是用两个指针的,为什么说用绝壁这个单词,,是因为我刷leetcode也有是十几题,再怎么菜也会提升点技能了,所以从两个指针入手,到底是从前往后还是从后往前,先在纸上画一画,找一找思路就好了,那么我的出来是整体从前往后,但是每次比较是比较后面的那个元素,两个指针,i和j,当A[i]==a[j]时j不动,i继续往后走,出现A[i]!=A[j]时,把A[i]赋值给A[j]即可,ij均往后走,如果还是不明白,拿出一张纸模拟下,你就会明白了。

看代码就更加清晰了:

 1 public class Solution { 2     public int removeDuplicates(int[] A) { 3         if(A.length==0) return 0; 4         int index=1; 5         for(int i=1;i<A.length;i++){ 6             if(A[i]!=A[i-1]){ 7                 A[index]=A[i]; 8                 index++; 9             }10         }11         return index;12            13     }14 }

 

leetcode------Remove Duplicates from Sorted Array