zoukankan      html  css  js  c++  java
  • [leetcode]26. Remove Duplicates from Sorted Array有序数组去重(单个元素只出现一次)

    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.

    题意:

    去除有序数组的重复元素,使得每个元素只能在数组中出现一次


    思路:

    仍然是在尽量不开新空间的情况下,

    直接在原数组中进行操作。

    指针i来遍历原数组。

    指针start 从 index 1 开始, 因为index 为 0 的元素是什么牛鬼蛇神都不重要。

    指针start 接受指针i扫过的、符合条件的元素。

    指针start 所到之处,便是新“数组”新生之时。


    代码:

     1 class Solution {
     2     public int removeDuplicates(int[] nums) {
     3         if(nums.length == 0) return 0;
     4         int start = 1;
     5         for(int i = 1; i < nums.length; i++){
     6             if(nums[i] != nums[start-1]){
     7                nums[start] = nums[i];
     8                start++;
     9             }
    10         }
    11       return start;  
    12     }
    13 }
  • 相关阅读:
    Django之信号
    Django缓存
    git简介
    Django request.path
    Django loaction.pathname 属性
    Ajax
    Anaconda 执行命令报ssl错误
    几行代码快速去掉迅雷临时文件的后缀
    win7 64 位安装 python,提示: 0x80240017-未指定的错误
    系统变量 %USERPROFILE%
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125439.html
Copyright © 2011-2022 走看看