Code9 delete duplicate items in sorted array

topic

leetcode26. Deleting duplicates in
a sorted array Given a sorted array, you need to delete repeated elements in place, so that each element only appears once, and return the new length of the removed array.
Don't use extra array space, you must modify the input array in situ and complete with O(1) extra space.

Example 1:
Given the array nums = [1,1,2], the
function should return the new length 2, and the first two elements of the original array nums are modified to 1, 2.
You don't need to consider the elements in the array beyond the new length.

Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4], the
function should return the new length of 5, and the first five elements of the original array nums are modified to 0 , 1, 2, 3, 4.
You don't need to consider the elements in the array beyond the new length.

Code

#include <vector>
using namespace std;

class Solution {
    
    
 public:
  // C++
  int removeDuplicates(vector<int>& nums) {
    
    
    if (nums.empty()) {
    
    
      return 0;
    }

    auto it = nums.begin();
    int val = *it;
    ++it;
    while(it != nums.end()){
    
    
      if (*it == val) {
    
    
        // erase返回值指向删除元素的下一位置
        it = nums.erase(it);
      }else{
    
    
        val = *it;
        ++it;
      }
    }

    return nums.size();
  }

  // C
  // 思路:快慢指针
  int removeDuplicates(int* nums, int numsSize) {
    
    
    if (0 == numsSize) {
    
    
      return 0;
    }

    int i = 0;
    for(int j = 1; j < numsSize; ++j){
    
    
      if (nums[j] != nums[i]){
    
    
        ++i;
        nums[i] = nums[j];
      }
    }

    return i + 1;
  }
};

Insert picture description here

test

#include <iostream>

void print(const vector<int>& nums) {
    
    
  cout << "nums : ";
  for(auto& i : nums) {
    
    
    cout << i << " ";
  }
  cout << std::endl;
}

int main() {
    
    
  std::vector<int> vc = {
    
    2, 2, 3, 4, 5, 5, 6, 7};
  print(vc);

  Solution s;
  s.removeDuplicates(vc);
  print(vc);

  std::cin.get();
  return 0;
}
  • result
nums : 2 2 3 4 5 5 6 7
nums : 2 3 4 5 6 7

Guess you like

Origin blog.csdn.net/luoshabugui/article/details/109468338