[Week 3] [Leetcode] [Array] Remove Duplicates from Sorted Array

来源:互联网 发布:手机怎么连接网络电视 编辑:程序博客网 时间:2024/06/03 09:10
  • Question:

    Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 being1 and2 respectively. It doesn't matter what you leave beyond the new length.

  • Analysis:

目标:根据题目了解到需要去除数组中重复的元素,并且整个运算过程不重新分配内存。

条件分析:首先这是一个已经排好序的数组,所以首先判断数组是否为空,如为空则直接返回0.其次,当数组不为空时,

  • Code:
    class Solution {public:    int removeDuplicates(vector<int>& nums) {        //考虑数组为空数组的情况,返回0        if (nums.empty())            return 0;                int index = 0;        for (int i = 1;i<nums.size();i++)        {            if (nums[index] != nums[i])                nums[++index] = nums[i];        }        return index+1;    }};


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