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 }
  • 相关阅读:
    数列分块入门 1-8
    最远点对 [线段树+树的直径]
    实验室外的攻防战 UOJ#180 [树状数组]
    二叉搜索树 [四边形不等式优化区间dp]
    树上的等差数列 [树形dp]
    序列 [树状数组+离散化]
    ATcoder1983 BBQ Hard
    8.18日报
    8.17日报
    8.16日报
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125439.html
Copyright © 2011-2022 走看看