LeetCode # Array # Easy # 26-Remove Duplicates from Sorted Array

topic:

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Problem analysis: Given an ordered repeated array, you are required to modify the array and return an array subscript, so that the subarray before the subscript has no repeated elements. Requires space complexity O(1).

Idea: You can't use other data structures, you can only directly modify the original array. Define a number end as an array subscript. When a non-repeated number is encountered, the number is copied to the position indicated by the subscript, and the subscript is moved back one place. After traversing the entire original array, starting from 0, the sub-array of length end is what the title requires.

1  public  class Solution {
 2      public  int removeDuplicates( int [] nums) {
 3          if (nums.length <= 1 ){
 4              return nums.length;
 5          }
 6          int len ​​= 1; // new length, at least 1 , the following loop starts from i=1 
7          for ( int i = 1; i < nums.length; i++ ){
 8              if (nums[i] != nums[i-1]){ // Not equal to the previous element, length+1 
9                  nums[len++] = nums[i]; // load new elements to the first len, then len++; 
10              }
11         }
12         return len;       
13     }
14 }

 Reference: https://www.2cto.com/kf/201507/415691.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324942315&siteId=291194637