Leetcode——26. Remove Duplicates from Sorted Array

来源:互联网 发布:苹果5s用不了4g网络 编辑:程序博客网 时间:2024/06/06 07:30

1. 概述

1.1 题目

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.

1.2 解题思路

这道题的思路和这篇文章: Leetcode——27. Remove Element很相似,也就是定义一个计数变量要是遇到相同的就不动,不同的就自加然后赋值。

2.  编码

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


阅读全文
0 0
原创粉丝点击