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 }
  • 相关阅读:
    如何用Tensorflow训练模型成pb文件和和如何加载已经训练好的模型文件
    hbase rowkey 设计
    hbase集群region数量和大小的影响
    为什么不建议在hbase中使用过多的列簇
    hive explode 行拆列
    通过livy向CDH集群的spark提交任务
    case when多条件
    spark sql/hive小文件问题
    SQL join
    spark任务调度模式,动态资源分配
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125439.html
Copyright © 2011-2022 走看看