Deletes duplicates in an ordered array

Return the new length of the array after deleting each element only once. Return the new length of the array after deleting the element.

Instead of using extra array space, you must modify the input array in place and do so using O(1) extra space.

See the LeetCode website for an example.

Source: LeetCode Link: https://leetcode-cn.com/probl… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: array traversal
  • First, if the array nums is empty or the length of array nums is zero, it returns zero directly.
  • Current records the current unrepeated index position, traverses the array, Pre records the previous bit value, when the current bit index value is equal to the value of Pre,index+1And then we keep traversing; If the value of the current bit is not equal to the value of the pre, update the value of current to the value of the current index bit, and move current back one bit (index+1), then move pre back continuously until the end of the traversal position.
public class LeetCode_026 { public static int removeDuplicates(int[] nums) { if (nums.length == 0) { return 0; } int current = 1; int index = 1; int pre = nums[0]; while (index < nums.length) { if (! (nums[index] == pre)) { nums[current++] = nums[index]; } pre = nums[index]; index++; } return current; } public static void main(String[] args) { int[] nums = new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; int result = removeDuplicates(nums); System.out.println(result); for (int num : nums) { System.out.print(num + " "); }}}

【 Daily Message 】
Even if there are through the ages, there are eight horizontal famine; The future is like the sea, the days ahead are long.