Removes duplicates from an ordered array
Given an ordered array nums, please delete the repeated elements in place, so that each element appears only once, return the new length of the array after deletion.
Instead of using extra array space, you must modify the input array in place and do so with O(1) extra space.
Examples can be found on the LeetCode website.
Source: LeetCode link: leetcode-cn.com/problems/re… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Solution 1: array traversal
- First, if the array nums is empty or has a length of 0, return 0.
- Pre records the value of the last bit. When the current bit of index is equal to the value of Pre,
index+1
Go back and forth; If the current bit is not the same as the pre bit, update the current bit to the current index bit and move current back one bit, index+1. Pre keeps moving back until the end of the loop.
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 + ""); }}}Copy the code
If there are thousands of years, there are eight famine; The future is as long as the sea.