zoukankan      html  css  js  c++  java
  • 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.

    思路:

    很巧妙的使用一个len的变量,使得我每次都在最外面如果i值与len不相等,都加1,

    如果相等不进行任何操作,这时候len不变化使得最终长度保持不变。

    代码:

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


  • 相关阅读:
    Git基本操作二
    Git基本操作一
    Mysql查询一
    接口的token验证
    Laravel模型的一些小技巧
    AOP编程思想实现全局异常处理
    5.4 RegExp类型
    5.4.1 RegExp实例属性
    5.4.2 RegExp实例方法
    5.4.3 RegExp构造函数属性
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519824.html
Copyright © 2011-2022 走看看