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 should 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
删除有序數組中重複的元素;傳回新的長度;不允許建立額外的數組
解決思路
- 設立2個遊标:遊标index用來周遊數組,遊标newLen用來插入元素
- 周遊數組,兩兩比較;如果不同,将index指向的元素複制到newLen指向位置;newLen與index各自右移
package com.rust.cal;
public class RemoveDuplicatesfromSortedArray {
public static int removeDuplicates(int[] nums) {
if (nums.length <= 1) {
return nums.length;
}
int index = 1;
int newLen = 1; // return value
while(index < nums.length){
if (nums[index] != nums[index - 1]) {
nums[newLen] = nums[index]; // insert element
newLen++;
}
index++;
}
return newLen;
}
public static void main(String args[]){
int[] input = {1,2,2,3,4,5,5,5,5,5,6,6,6,7,7,7,7,8};
System.out.println("new lengh: " + removeDuplicates(input));
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + " ");
}
}
}
輸出:
new lengh: 8
1 2 3 4 5 6 7 8 5 5 6 6 6 7 7 7 7 8