5

(Remove Duplicates from Sorted Array)

 2 years ago
source link: https://tianrunhe.wordpress.com/2012/08/25/remove-duplicates-from-sorted-array/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

(Remove Duplicates from Sorted Array)

25 Aug 2012 5 Comments

by Runhe Tian in LeetCode Tags: Array, C++, Java

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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].

Thoughts:
This question is actually simpler than what it looks. We just need one scan with two pointers. The first pointer points to the last index of subarray with distinct elements (hence it starts with 0). The second pointer goes through the array, starting from index 1.If the numbers referred by two pointers are different, we pad the number from back to head.

Code (Java):

public class Solution {
public int removeDuplicates(int[] A) {
int j = 0;
if(A.length == 0)
return 0;
for(int i = 1; i < A.length; ++i) {
if(A[i] != A[j]) {
j++;
A[j] = A[i];
}
}
return j + 1;
}
}

Code (C++):

class Solution {
public:
int removeDuplicates(int A[], int n) {
int j = 0;
if(n == 0)
return 0;
for(int i = 1; i < n; ++i) {
if(A[i] != A[j]) {
j++;
A[j] = A[i];
}
}
return j + 1;
}
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK