zoukankan      html  css  js  c++  java
  • LeetCode--Array--Remove Duplicates from Sorted Array (Easy)

    26. Remove Duplicates from Sorted Array (Easy)

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

    solution##

    解法一

    class Solution {
        public int removeDuplicates(int[] nums) {
            int newlength = 0, k = 0;
            for (int i = 0; i < nums.length - 1; i++)
            {
                if (nums[i] < nums[i+1])   //如果两数不同
                {
                    k = i + 1;     //记录不同两数中下一个的下标
                    newlength++;   //新数组长度++
                    if (k > newlength)    //如果k与newlength不同步,说明有重复的数
                        nums[newlength] = nums[k];  将nums[k]移动到newlength处
                }
            }
            return newlength + 1;    //此处不能用newlength++
        }
    }
    

    解法二

    class Solution {
        public int removeDuplicates(int[] nums) {
            int newlength = 0;
            for (int i = 0; i < nums.length; i++)
            {
                if (nums[newlength] != nums[i])
                    nums[++newlength] = nums[i];
            }
            return newlength+1;  //此处不能用newlength++
        }
    }
    

    总结##

    题意是给定一个排好序的数组,需要将里面不重复的数字按顺序放在数组左端,构成一个新的数组,且这些不重复数字的长度为length,超过length长度的数字不用理会。
    第一种解法没第二种解法简单,故只描述第二种解法。第二种解法的思路是设置一个计数器newlength,初始值为0,然后遍历数组,如果nums[newlength] != nums[i],则将nums[++newlength]置为nums[i],否则什么都不做;遍历完成后返回newlength+1;

    Notes
    1.注意++i与i++的区别;

  • 相关阅读:
    卫星时间同步装置的安装及售后
    windowsU盘重装系统:操作流程
    vue安装正确流程
    win10以太网未识别的网络
    [UnityShader]unity中2D Sprite显示阴影和接受阴影
    [UnityShader]说厌了的遮挡显示
    [Unity]利用Mesh绘制简单的可被遮挡,可以探测的攻击指示器
    ConcurrentHashMap源码解读
    Vector底层原理
    LinkedList集合底层原理
  • 原文地址:https://www.cnblogs.com/victorxiao/p/11143936.html
Copyright © 2011-2022 走看看