zoukankan      html  css  js  c++  java
  • 26. Remove Duplicates from Sorted Array*(快慢指针)

    description:

    Given a sorted array nums, 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.
    Note:

    Example:

    Example 1:
    
    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 returned length.
    Example 2:
    
    Given nums = [0,0,1,1,1,2,2,3,3,4],
    
    Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
    
    It doesn't matter what values are set beyond the returned length.
    

    my answer:

    感恩

    快慢指针,慢的指向的一直都是新的,也就是说来一个新的它才往前走一步,快的就是不断向前,发现和慢的不一样的就汇报给那个慢的,然后慢的更新。如果二者相等,则慢的不动,快的前进一步;如果二者不等,则慢的前进一步的同时更新那个新一步指向的数字为现在快指针指向的新数字,快的同时也往前走一步。

    
    

    大佬的answer:

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if(nums.empty()) return 0;
            int n = nums.size();
            int pre = 0, cur = 0;
            while(cur<n){
                if(nums[pre] == nums[cur]){
                    cur++;
                }else{
                    nums[++pre] = nums[cur++];
                }
            }return pre+1;
        }
    };
    

    relative point get√:

    hint :

  • 相关阅读:
    string.Format组合跳转路径
    jquery 设置asp:dropdownlist 选中项
    asp:UpdatePanel中js失效问题已解决
    repeater 一个td多个div显示图片
    aps.net js获取服务器控件
    nfs—文件转换器
    Linux之文件权限
    关于Linux与Windows的在服务器的一些区别
    关于Linux目录结构的理解
    新的旅程
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10889152.html
Copyright © 2011-2022 走看看