W********e 发帖数: 45 | 1 remove duplicate in sorted array这道题,虽然现在leetcode已经没有这题了,只有
follow up 的judge。不过我还是写了一段代码,顺便用leetcode来judge一下。不知道
为什么我在A数组最后加了一个结束符,就出现run time error了?而我用c-free验证
却没问题?代码如下,麻烦大家了!
class Solution {
public:
int removeDuplicates(int A[], int n) {
int newArrIndex=0,index=0,newlen=0;
if(n==0)
return 0;
while(index
{
if(A[index]==A[index+1])
{
A[newArrIndex]=A[index];
}
else
{
A[newArrIndex]=A[index]; //这种情况包括了A【index+1】是结束符
的情况
newArrIndex++;
newlen++;
}
index++;
}
A[newArrIndex]='\0'; //到底要不要加结束符?????????
return newlen;
}
}; | o****d 发帖数: 2835 | 2 1 why you need to add '\0', it is not a c string.
2 A[index+1] is out of array bound when index is n-1
3 if the input does not have duplicates, what happens when you add '\0'?
【在 W********e 的大作中提到】 : remove duplicate in sorted array这道题,虽然现在leetcode已经没有这题了,只有 : follow up 的judge。不过我还是写了一段代码,顺便用leetcode来judge一下。不知道 : 为什么我在A数组最后加了一个结束符,就出现run time error了?而我用c-free验证 : 却没问题?代码如下,麻烦大家了! : class Solution { : public: : int removeDuplicates(int A[], int n) { : int newArrIndex=0,index=0,newlen=0; : if(n==0) : return 0;
|
|