您的位置:首页 > 其它

【leetcode】26. Remove Duplicates from Sorted Array

2016-07-05 00:40 309 查看

题目描述:

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.

解题分析:

扫描一遍链表,用一个变量标记已找到的不重复的元素的长度len,每当找到不重复元素时,就让被扫描元素与变量len标记的元素交换位置即可

具体代码:

public class Solution {
public static int removeDuplicates(int[] nums) {
if(nums.length<=1)
return nums.length;
int num =nums[0];
int len =1;
for(int i=1;i<nums.length;i++){
if(num!=nums[i]){
num=nums[i];
nums[len]=nums[i];
len++;
}
}
return len;
}

}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: