leetcode-26 Remove Duplicates from Sorted Array

前端之家收集整理的这篇文章主要介绍了leetcode-26 Remove Duplicates from Sorted Array前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


问题描写:

Givena sorted array,remove the duplicates in place such that each element appearonly once and return the new length.

Do not allocate extra space for another array,youmust do this in place with constant memory.

For example,
Given input array A = 
[1,1,2],

Your function should return length = 2.

问题分析:使用1个count统计不同的元素个数,然后注意A[count] = A[i]来消除重复元素便可

代码

public class Solution { public int removeDuplicates(int[] A) { if(A == null || A.length == 0) return 0; int count = 1; for(int i = 1; i < A.length; i++) { if(A[i] != A[i - 1]) { //更新A[count] A[count] = A[i]; //更新count count ++; } } return count; } }

猜你在找的PHP相关文章