LeetCode(28)-Remove Duplicates from Sorted Array

来源:互联网 发布:python开源网站源码 编辑:程序博客网 时间:2024/06/05 18:52

题目:

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.

思路

  • 题意是把有序数组的重复元素去掉,返回不重复元素的个数n,至于后面的元素怎么排列没有要求,前n个必须是不重复的元素,相对顺序不变
  • 设置两个变量,一个用来存放最后一个不重复数的坐标,一个用来往下比较看是不是初夏重复
  • -

代码

public class Solution {    public int removeDuplicates(int[] nums) {        if(nums == null){            return 0;        }        if(nums.length == 1){            return 1;        }        int n = nums.length;        int j = 0;        for(int i = 0; i < (n-1);i++){            if(nums[i] != nums[i+1]){                nums[j++] = nums[i];            }            if(i == (n-2)){                nums[j] = nums[n-1];            }        }        return (j+1);    }}
0 0
原创粉丝点击