zoukankan      html  css  js  c++  java
  • Remove Duplicates From Sorted Array leetcode java

    算法描述:

    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 in place with constant memory.

    For example,
    Given input array 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.

    算法分析:一个有序数组,出去其中出现次数大于1的数,返回剩余元素个数

    代码:设置两个指针,i 遍历原数组,是去除重复后的下标

    public int removeDuplicates(int[] nums) {
            if(nums == null || nums.length == 0)
                return 0;
            int len = nums.length;
            int j = 1; //数组第一个元素是不需要变的,所以长度至少为1
            for(int i = 1; i < len; i++){ //数组遍历从下标1开始
                if(nums[i] == nums[i - 1])
                    continue;
                else {
                    nums[j++] = nums[i];
                }
            }
            
            return j;
        }
  • 相关阅读:
    并发
    基础概念总结
    Tomcat总结
    JVM总结
    Spring事务管理
    数据结构和算法
    拦截器
    关于XML fragments parsed from previous mappers already contains value for错误的探索
    zookeeper比较好的学习地址
    关于idea中的maven打包
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5051127.html
Copyright © 2011-2022 走看看