zoukankan      html  css  js  c++  java
  • 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 by modifying the input array in-place with O(1) extra memory.

    Example:

    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 new length.

    从一个有序数组中删除重复的元素。要求:不允许使用额外数据结构,只能在当前数组中操作,返回去除重复元素后的数组长度x,且原数组中前x个元素就是不重复的x个元素,但是x后面的元素不管。。

    思路就是,当前数组也代替新数组,用来存放不重复的元素,从前开始存放。就是用两个指针,一个用于遍历,一个代表新数组添加元素

    class Solution {
        public int removeDuplicates(int[] nums) {
            if(nums==null||nums.length==0)
                return 0;
            if(nums.length==1)
                return 1;
            int count=1; //该指针用于添加元素,i用于遍历数组由于count始终小于或等于i,所以i会正确遍历到数组所有元素
           for(int i=1;i<nums.length;i++){
               if(nums[i]>nums[count-1])
                   nums[count++]=nums[i];
           }
            return count;
        }
    }

    代码解析:count表示不重复元素的下标,i表示遍历当前数组的元素。当当前元素大于不重复数组的最后一个元素,就将元素存进去。一开始是需要第二个元素跟第一个元素比较,count=1是因为num[i]在i=1时应该要存放到num[1]位置上了,如果count=0,nums[i]>nums[count],i从1开始,也是后一个跟前一个比较,也是符合规则的,但是nums[count++]=nums[i]会将第二个元素存到了第一个元素的位置,就会向前串一位了,所以不行。

    
    
  • 相关阅读:
    Casperjs循环执行(重复执行不退出)
    casperjs批量执行多个url
    CasperJS API介绍
    phantomjs waitFor
    phantomjs 长图截屏
    Linux Shell函数
    全废话SQL Server统计信息(2)——统计信息基础
    JavaScript推断undefined的技巧
    Activity Test1
    Android触摸事件(五)-CropBitmapActivity关于裁剪工具的使用
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8059611.html
Copyright © 2011-2022 走看看