1.这个题不难,关键在于把题目意思理解好了。这个题问的不清楚。要求return new length,很容易晕掉。
其实就是return 有多少个单独的数。
import java.util.Arrays; /* * Question: 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. */ public class RemoveDuplicatesfromSortedArray { public static void main(String[] args){ int[] nums = new int[]{1,1,2}; removeDuplicates(nums); } public static int removeDuplicates(int[] nums){ if(nums == null || nums.length == 0){ return 0; } int index = 1; for(int i=1 ;i<nums.length;i++){ if(nums[i] != nums[i-1]){ index ++; } } nums = Arrays.copyOf(nums, index); return index; } public static int removeDuplicatesWorking(int[] nums){ return 0; } }