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.

    题目解答:

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

    题目发散:

    上面的代码是自己在编程的时候直接反应写出来的答案。AC之后,想到了C++的STL中,有一个函数unique也可以实现对有序数组的一个去重。

    unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

    需注意的是:unique返回的是一个迭代器,即出现重复的第一个位置。

    [1 , 1,  2 , 2 , 3 , 4]

    使用unique之后得到的数组,如下

    [1 , 2 , 3 , 4 , 1 , 2]

    对于上面的这个数组,begin指向1,end指向最末的2的后面的一个位置,那么unique返回的迭代器指向下面这个数组的第二个1的位置。

    于是便重新写了下面这个。

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if(nums.size() <= 1)
                return nums.size();
            vector<int>::iterator nums_end_it = unique(nums.begin(),nums.end());
            return nums_end_it - nums.begin();
        }
    };
  • 相关阅读:
    写给理工科人看的乐理(一)声学基础
    魔方最少记忆还原法
    甲乙两人互猜数字(鬼谷子问题)的逻辑推理与算法建模
    模板元编程实现素数判定
    UVa OJ 194
    UVa OJ 175
    UVa OJ 197
    UVa OJ 180
    UVa OJ 140
    判断input或者div.span等标签是否存在
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5181146.html
Copyright © 2011-2022 走看看