您的位置:首页 > 职场人生

LeetCode(28)-Remove Duplicates from Sorted Array

2016-04-06 22:32 627 查看

题目:

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息