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 :

  • 相关阅读:
    hdu1881(贪心+dp)
    hdu1513(最长公共子序列)
    关于布局的一点心得
    android字符串工具类
    android系统时间格式转换工具类
    android sp文件一个键值保存多条信息
    android 对话框显示工具类
    android网络连接工具类
    日志打印工具类
    关于项目中的一些经验:封装activity、service的基类,封装数据对象
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10889152.html
Copyright © 2011-2022 走看看