(算法分析Week9)Remove Duplicates from Sorted Array[Easy]

来源:互联网 发布:java math.random用法 编辑:程序博客网 时间:2024/05/18 23:25

26. Remove Duplicates from Sorted Array[Easy]

题目来源

Description

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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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.

Solution

一个水题放松一下。
一个已经排好序的数组,删除重复元素,即只用和自己左边的数比较就好。
不允许用额外的空间,否则直接new一个数组存数。
我用的方法是从第二个元素(下标为1)开始,数重复个数长度(length),直到第一个和先前不重复的元素出现,插在(i-length)的位置,就是说到目前为止有i个元素,其中length个是重复的,那i-length就是第一个重复的元素位置。不停循环,最后返回处理后的数组长度。

Complexity analysis

O(n)

Code

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

Result

这里写图片描述

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