zoukankan      html  css  js  c++  java
  • (leetcode题解)Remove Duplicates from Sorted Array

    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 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 new length.

    这道题要求删除给定排列好的数组中重复的数子,记录剩余的数组大小。

    运用两个指示下标,直接比较相邻两个数,相同就剔除第二个,不同则保留。

    C++实现如下:

    int removeDuplicates(vector<int>& nums) {
            if(nums.empty())
                return 0;
            int res=1;
            for(int i=1,j=0;i<nums.size();)
            {
                if(nums[j]!=nums[i])
                {
                    nums[++j]=nums[i];
                }
                else 
                    i++;
                res=j+1;
            }
            return res;
        }
  • 相关阅读:
    015-面向对象
    017-错误和异常
    019-File
    020-OS
    021-模块
    022-标准库
    数据库目录
    数据库 概念详解
    MySQL 基础
    MySQL 数据库操作
  • 原文地址:https://www.cnblogs.com/kiplove/p/6972237.html
Copyright © 2011-2022 走看看