LeetCode 26. Remove Duplicates from Sorted Array
Remove Duplicates from Sorted Array
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 shocould 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.
Train of Thought: This question is relatively simple. The general idea is to delete the repeated vertices in the array and then return the length of the new array. The first n in the array is the new array. The only difficulty is that no additional space is available.
The Code is as follows:
Public class Solution {public int removeDuplicates (int [] nums) {if (nums. length <= 1) {return nums. length;} int len = 1; // new length, at least 1. the following cycle starts from I = 1 for (int I = 1; I <nums. length; I ++) {if (nums [I]! = Nums [I-1]) {// not equal to the previous element, Length + 1 nums [len ++] = nums [I]; // Add new elements to the first len} return len ;}}