Tuesday, July 2, 2013

Remove Duplicates from Sorted Array II@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
» Solve this problem

此题的基本思路还是和remove duplicates from sorted array一样,就是双指针,i and j,i 指向当前已经去掉了duplicate的subarray,j就一直往后搜寻,一直遇到和i指向的不同的,就做A[++i]=A[j].

此题多设了一个counter来看是否是两个了,有一些细节需要注意,但总体不难。看代码可知。




class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=1) return n;
int count=0, i=0;
for(int j=1; j<n; j++)
{
if(A[i]==A[j]&&count<2)
{
count=2;
A[++i]=A[j];
}
else if(A[i]!=A[j])
{
A[++i]=A[j];
count=0;
}
else if(count==2&&A[i]==A[j])
continue;
}
return i+1;
}
};

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...