题目描述:
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标记的元素交换位置即可
具体代码:
1 public class Solution { 2 public static int removeDuplicates(int[] nums) { 3 if(nums.length<=1) 4 return nums.length; 5 int num =nums[0]; 6 int len =1; 7 for(int i=1;i<nums.length;i++){ 8 if(num!=nums[i]){ 9 num=nums[i]; 10 nums[len]=nums[i]; 11 len++; 12 } 13 } 14 return len; 15 } 16 17 }
时间: 2024-11-03 03:27:05