zoukankan      html  css  js  c++  java
  • [LeetCode]26、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.

    思路:

    从已经排好序的数组中删除重复的元素,返回最后的长度。只能在本链表中进行,不能申请额外的空间。
    设置一个index作为索引位,当当前元素不等于它的前一位时,将当前元素的值赋予索引位元素。不断向后遍历,即可跳过重复元素,最后返回index的值即为不重复元素的数量。

     1 public class Solution26 {
     2     public int removeDuplicates(int[] nums) {
     3         if(nums == null || nums.length == 0){return 0;}
     4         int index = 1;
     5         for(int i = 1; i < nums.length; i++){
     6             if(nums[i] != nums[i-1]){
     7                 nums[index]=nums[i];
     8                 index++;
     9             }
    10         }
    11         return index;
    12         }
    13     public static void main(String[] args) {
    14         // TODO Auto-generated method stub
    15         Solution26 solution26 = new Solution26();
    16         int[] nums = {1,1,2};
    17         System.out.println(solution26.removeDuplicates(nums));    
    18     }
    19 
    20 }
    
    
  • 相关阅读:
    springMVC之配置
    compareTo(String str)与compareToIgnoreCase(String str)
    js中的json
    Java转json
    mxnet 豆瓣镜像源安装
    查看 tensorflow 是GPU版本 还是CPU版本
    nvidia-docker安装
    ubuntu下安装tensorflow-gpu版本过程
    CUDA, CUDNN 版本查询
    ubuntu版本查看命令
  • 原文地址:https://www.cnblogs.com/zlz099/p/8144912.html
Copyright © 2011-2022 走看看