美文网首页LeetcodeAndroid开发经验谈程序员
不新建数组完成数据去重问题

不新建数组完成数据去重问题

作者: Dynamic_2018 | 来源:发表于2017-11-10 14:39 被阅读31次

    题外话:除了业务逻辑,我们应该还需要关注代码的艺术,编程之美。慢慢的把涉及到算法 数据结构 典型的操作基本类型的例子记录下来。
    leetcoode

    题目

    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.

    思路

    抓住关键 已排序(未排序也不可能0(1)完成)、不可再分配空间
    当然这道题是一道esay 弄清题意后 很容易想到用快慢指针来记录,快指针遍历玩数组,慢指针记录新的数组,但是指向同一个数组。

    代码

    class Solution {
        public int removeDuplicates(int[] nums) {
            //注意是排序后的数组  用两个指针去跟踪
            int fast = 0;
            int slow = 0;
            for( ;fast<nums.length;fast++){
                if(nums[fast] != nums[slow]){ //如果不一样 说明又多了一个独立的元素
                    slow ++;
                    nums[slow] = nums[fast];//一样时,这里还要把满指针的数据也改了,避免没有及时更新数组,漏掉快指针下一个重复的数据。
                }else{
                      
                }
            }
            return slow+1;
            
        }
    }
    

    ps:

    主要是排序好的数组就比较好操作了,慢指针需要及时更新数据,不然不能通过所有case。

    相关文章

      网友评论

        本文标题:不新建数组完成数据去重问题

        本文链接:https://www.haomeiwen.com/subject/ivubmxtx.html