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;
        }
  • 相关阅读:
    PTA 7-6 列出连通集(深搜+广搜)
    TZOJ 2648 小希的迷宫(并查集)
    HDU 3342 Legal or Not(拓扑排序)
    哈夫曼树
    mst
    [THUWC2017]随机二分图
    视察
    [bzoj3274]Circle
    [bzoj3273]liars
    求导相关
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5051127.html
Copyright © 2011-2022 走看看