LeetCode Notebook 2020-2021
  • 序
  • 目录
  • 线性表
    • 数组
      • Remove Duplicates from Sorted Array
      • Remove Duplicates from Sorted Array II
      • Exercises I
      • Search in Rotated Sorted Array
      • Search in Rotated Sorted Array II
      • Median of Two Sorted Arrays
      • Longest Consecutive Sequence
      • Exercises II
      • Two Sum
      • 3Sum
      • 3Sum Closest
      • 4Sum
      • Exercises III
      • Next Permutation
      • Permutation Sequence
      • Exercises IV
      • Valid Sudoku
      • Trapping Rain Water
      • Rotate Image
      • Plus One
      • Exercises V
      • Climbing Stairs
      • Set Matrix Zeroes
      • Gray Code
      • Gas Station
      • Exercises VI
      • Candy
      • Single Number
      • Single Number II
      • Exercises VII
    • 链表
      • Add Two Numbers
      • Reverse Linked List II
      • Partition List
      • Swap-nodes-in-pairs
  • 字符串
    • 字符串
      • Valid Palindrome
      • Implement strStr()
      • String to Integer(atoi)
      • Add Binary
      • Longest Palindromic Substring
      • Longest Common Subsequence
      • Regular Expression Matching
      • Rearrange Spaces Between Words
      • Longest Common Prefix
      • Wildcard Matching
      • subdomain visit count
  • 栈和队列
    • 栈
      • Min Stack
      • Valid Parentheses
    • 队列
  • 树
    • 二叉树的遍历
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Binary Tree Postorder Traversal
      • Search in a Binary Search Tree
    • 二叉树的构造
      • Untitled
    • 二叉查找树
      • Validate Binary Search Tree
    • 二叉树的递归
      • Untitled
  • 图
    • 图
  • 排序
    • 排序
      • Merge Sorted Array
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
      • Exercises I
      • Insertion Sort List
      • Sort List
      • Sort Color
      • First Missing Positive
      • Exercises II
  • 查找
    • 查找
      • Random Pick with Weight
      • Prefix and Suffix Search
      • Search Insert Position
      • Search a 2D Matrix
  • BFS
    • BFS
  • DFS
    • DFS
      • Split a String Into the Max Number of Unique Substrings
      • Palindrome Partitioning
      • Unique Path
      • Unique Path II
  • 动态规划
    • DP
      • Coin Change
      • Maximal Rectangle
      • Super Egg Drop
      • Exercises
      • Best Team With No Conflicts
  • 分治法
    • Divide And Conquer
  • 贪心法
    • Greedy
      • Jump Game
      • Jump Game II
      • Best time to buy and sell stock
      • Best time to buy and sell stock II
      • Container with most water
      • Exercises
  • 暴力枚举
    • Brute Force
      • Subsets
      • Subsets II
      • Permutation
      • Permutation II
      • Combinations
      • Letter Combinations of a Phone Number
  • others
    • 小岛题
    • 滑动窗口
      • Longest substring without repeating characters
      • Sliding Window Maximum
      • Max Consecutive One III
      • Count Number of Nice Subarrays
    • Roman number code
    • Untitled
由 GitBook 提供支持
在本页
  • Remove Duplicates from Sorted Array
  • 描述
  • 例子
  • 解法一
  • 解法二
  • 解法三
  • 总结

这有帮助吗?

  1. 线性表
  2. 数组

Remove Duplicates from Sorted Array

Easy 原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/

上一页数组下一页Remove Duplicates from Sorted Array II

最后更新于4年前

这有帮助吗?

Remove Duplicates from Sorted Array

原题链接:

描述

Given a sorted array nums, remove the duplicates such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array with O(1) extra memory.

例子

Given nums = [1,1,2],

Your function should return length =2, with the first two elements of nums being 1 and 2 respectively,

It doesn't matter what you leave beyond the returned length.

  • 注意

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

解法一

使用index,在原数组上做remove

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        int index = 0;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[index] != nums[i]) nums[++index] = nums[i];
        }
          return index + 1;
    }
};

或者

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        int index = 0;
        int n=nums.size();
        for(int i = 1; i < n; i++){
            if(nums[i] == nums[i-1]) index++;
            else nums[i-index] = nums[i];
        }
        return n-index;
    }
};

分析:

T=O(n), S=O(1)

解法二

使用STL的distance和unique

关于distance:

Calculates the number of elements between first and last.

关于unique:

Removes all but the first element from every consecutive group of equivalent elements in the range [first,last).

class Solution {
    public:
    int removeDuplicates(vector<int>& nums) {
        return distance(nums.begin(), unique(nums.begin(), nums.end()));
    } 
};

分析:

根据STL中unique是使用双指针实现的:

template <class ForwardIterator>
  ForwardIterator unique (ForwardIterator first, ForwardIterator last)
{
  if (first==last) return last;

  ForwardIterator result = first;
  while (++first != last)
  {
    if (!(*result == *first))  // or: if (!pred(*result,*first)) for version (2)
      *(++result)=*first;
  }
  return ++result;
}

解法三

改写unique,使用upper_bound

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        return distance(nums.begin(), removeDuplicates(nums.begin(),nums.end(), nums.begin()));
    }
    template<typename InIt, typename OutIt>OutIt removeDuplicates(InIt first, InIt last, OutIt output) {
        while (first != last) {
            *output++ = *first;
            first = upper_bound(first, last, *first);
        }
        return output;
    }
};

分析:

总结

题目开始,联想到快慢指针的方法。如果对STL熟悉,可以想到unique函数来进行解题,但是题目提示为sorted array,所以unique的解法不一定是最优解。在理解unique的原理和分析题目的基础上,作出变形改写。

https://leetcode.com/problems/remove-duplicates-from-sorted-array/
in-place
in-place
http://cplusplus.com/reference/iterator/distance/?kw=distance
http://cplusplus.com/reference/algorithm/unique/?kw=unique