zoukankan      html  css  js  c++  java
  • LeetCode OJ 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 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.

    Subscribe to see which companies asked this question

    【思路】

    1. 举个例子[1,1,1,2,2,2,3,4,5],我的想法就是找到每一节重复数字的长度,然后把后面的数字向前移动,直到遍历到数组最后。

    上述例子中,我们从头开始发现有1重复出现了3次,因此我们把1后面的数字向前移动2,变为[1,2,2,2,3,4,5],然后把数组的len变为len-2,重复上面的结果直到遍历到最后。但是这个方法的效率并不高,每发现一个重复的元素都要把后面的数字向前移动,有没有更好的思路呢?

    2. 一个更好的方法是:我们维持两个变量,i 用来遍历数组,j 用来指示数组中不重复的那部分的最后一个值的下标。在遍历数组的过程中,如果当前值和前一个值不同,则nums[++j] = nums[i],否则的话继续向前遍历。形象化的过程如下:

    • j = 0; i = 1;

    • nums[i] 等于 nums[i-1];

    • nums[i] 不等于 nums[i-1]; nums[++j] = nums[i];

    • 省略若干步


    【java代码1】

     1 public class Solution {
     2     public int removeDuplicates(int[] nums) {
     3         if(nums==null || nums.length==0) return 0;
     4         int len = nums.length;
     5         int duplen = 0;
     6         for(int i = 0; i < len - 1; i++){
     7             duplen = 0;
     8             for(int j = i + 1; j < len; j++){
     9                 if(nums[j] == nums[i]) duplen++;
    10                 else break;
    11             }
    12             if(duplen > 0){
    13                 for(int k = i + duplen + 1; k < len; k++){
    14                     nums[k-duplen] = nums[k];
    15                 }
    16                 len = len - duplen;
    17             }
    18         }
    19         return len;
    20     }
    21 }

     【java代码2】

     1 public class Solution {
     2     public int removeDuplicates(int[] nums) {
     3         if (nums.length == 0)
     4             return 0;
     5         int j = 0;
     6         for(int i=1; i<nums.length; i++) {
     7         if (nums[i-1] != nums[i])
     8             nums[++j] = nums[i];
     9         }
    10         return j;
    11     }
    12 }
  • 相关阅读:
    出现Unexpected token, expected ","报错原因
    select属性的作用
    程序员无广告版百度
    VUE核心组件
    ajax的作用
    SSH整合
    Unity安装教程
    bean的生命周期
    BeanFactory
    打印机
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5510663.html
Copyright © 2011-2022 走看看