Leetcode: Remove Duplicates from Sorted Array

朱雀 2022-08-07 06:48 115阅读 0赞

题目:
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: Remove Element
都是通过定义一个伪指针,这个指针记录满足要求的数据位置,当前数据满足要求的时候(不用删除的时候)指针移动一位,最后返回这个伪指针的值。

C++参考代码:

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

C#参考代码:

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

Python参考代码:

  1. class Solution:
  2. # @param a list of integers
  3. # @return an integer
  4. def removeDuplicates(self, A):
  5. count = len(A)
  6. if count == 0:
  7. return 0
  8. pt = 1
  9. for i in range(1, count):
  10. if A[i - 1] != A[i]:
  11. A[pt] = A[i]
  12. pt += 1
  13. return pt

Java参考代码:

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

发表评论

表情:
评论列表 (有 0 条评论,115人围观)

还没有评论,来说两句吧...

相关阅读