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;
        }
  • 相关阅读:
    代码面试最常用的10大算法
    ant google compiler 压缩
    美工资源
    面试题
    validate表单验证插件
    laypage分页
    layer弹出框小结
    Thymeleaf
    webApp开发
    grunt自动化构建工具
  • 原文地址:https://www.cnblogs.com/kiplove/p/6972237.html
Copyright © 2011-2022 走看看