返回介绍

Remove Duplicates from Sorted Array

发布于 2025-02-22 13:01:23 字数 1871 浏览 0 评论 0 收藏 0

Source

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

Example

题解

使用两根指针(下标),一个指针(下标) 遍历数组,另一个指针(下标) 只取不重复的数置于原数组中。

C++

class Solution {
public:
  /**
   * @param A: a list of integers
   * @return : return an integer
   */
  int removeDuplicates(vector<int> &nums) {
    if (nums.size() <= 1) return nums.size();

    int len = nums.size();
    int newIndex = 0;
    for (int i = 1; i< len; ++i) {
      if (nums[i] != nums[newIndex]) {
        newIndex++;
        nums[newIndex] = nums[i];
      }
    }

    return newIndex + 1;
  }
};

Java

public class Solution {
  /**
   * @param A: a array of integers
   * @return : return an integer
   */
  public int removeDuplicates(int[] nums) {
    if (nums == null) return -1;
    if (nums.length <= 1) return nums.length;

    int newIndex = 0;
    for (int i = 1; i < nums.length; i++) {
      if (nums[i] != nums[newIndex]) {
        newIndex++;
        nums[newIndex] = nums[i];
      }
    }

    return newIndex + 1;
  }
}

源码分析

注意最后需要返回的是索引值加 1。

复杂度分析

遍历一次数组,时间复杂度 O(n)O(n)O(n), 空间复杂度 O(1)O(1)O(1).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文