leetcode-26 Remove Duplicates from Sorted Array

来源:互联网 发布:语c kg是什么意思网络 编辑:程序博客网 时间:2024/06/05 20:40

问题描述

地址:https://leetcode.com/problems/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 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.
翻译:给出一个排好序的数组,删除重复的项,使得每个元素只出现一次,并返回非重复元素的长度
注意:不要为另一个数组开辟新的空间,必须使用不变的内存空间

比如:
给出输入数组:nums = [1,1,2],
方法应该返回2,并且数组最开始的两个元素分别是1 和2。新的数组长度以外的元素可以不用关心

问题解析

这里写图片描述

这里写图片描述

这里写图片描述

解析代码

上述解析过程针对通用的这类数组去重问题,但是leetcode-26这个题目,需要的最终结果是新数组的长度,所以代码中设置了k来记录。每当nums[i] != nums[j]时,k需要递增。

public class RemoveDuplicatesfromSortedArray {    @Test    public void test(){        int[] nums = {1,1,2};        int result =removeDuplicates(nums);        System.out.println("1");    }    public int removeDuplicates(int[] nums) {        int k = 0;        int i = 0;        int j = 0;        while (j < nums.length) {            if (nums[i] == nums[j]) {                j++;                continue;            }            k++;            nums[i+1] = nums[j];            i = i+ 1;            j++;        }        return k + 1;    }}
1 0
原创粉丝点击