zoukankan      html  css  js  c++  java
  • Leetcode 26. 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 A = [1,1,2],

    Your function should return length = 2, and A is now [1,2].

    二、题目分析

    分析:该题目的要求中的关键字,排序,数组,不可以申请额外空间。

    对于数组而言,删除重复的元素就会很困难,因此只可以是用 (将要保留的)非重复的元素覆盖掉重复的元素。

    1.自己的思路:

      首先,统计非重复的元素的个数,与此同时,用一个值把所有重复的元素代替掉

      然后,把非重复的元素一一前移。

    2.最简洁的思路:

      利用两个指针,遍历一次该数组,用不重复的元素覆盖重复的元素

    三、代码

    public class Solution {
        public int removeDuplicates(int[] nums) {
            if(nums.length==0)
                return 0;
            int j=0;//指向每一个不重复的元素
            for(int i=0;i<nums.length;i++ ){
                if(nums[i]!=nums[j]){
                    nums[++j]=nums[i];
                }
            }
            return ++j;
        }
    }
    

      

  • 相关阅读:
    使用VisualStudio进行单元测试之二
    使用VisualStudio进行单元测试之一
    ExtJS监听键盘事件:回车键实现登录功能
    PPTP无法连网
    Android深度探索.
    Android深度探索
    Android驱动开发
    window.open()的具体使用方法
    js控制的几种页面跳转和传值(转载)
    Hatching shader
  • 原文地址:https://www.cnblogs.com/lyr2015/p/6386337.html
Copyright © 2011-2022 走看看