26.Remove Duplicates from Sorted Array

女爷i 2022-06-09 03:55 298阅读 0赞
  1. /*
  2. Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
  3. Do not allocate extra space for another array, you must do this in place with constant memory.
  4. For example,
  5. Given input array nums = [1,1,2],
  6. 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.
  7. */
  8. //解法一 7% 172ms
  9. int removeDuplicates(int* nums, int numsSize) {
  10. int i,j;
  11. for(i=0;i<numsSize-1;i++)
  12. if(nums[i]==nums[i+1])
  13. {
  14. for(j=i;j<numsSize-1;j++)
  15. {
  16. nums[j] = nums[j+1];
  17. }
  18. numsSize--;
  19. i--;
  20. }
  21. return numsSize;
  22. }
  23. //解法二 23% 19ms
  24. /*
  25. 这里我参考了27. Remove Element 题目第二种做法对算法进行改进,机理是相同的
  26. */
  27. int removeDuplicates(int* nums, int numsSize) {
  28. int i,count = 1;
  29. if(nums[0]==NULL&&numsSize==0)
  30. return NULL;
  31. for(i=0;i<numsSize-1;i++)
  32. if(nums[i]!=nums[i+1])
  33. nums[count++] = nums[i+1];
  34. return count;
  35. }
  36. //解法三 69% 12ms
  37. int removeDuplicates(int* nums, int numsSize) {
  38. int i, j;
  39. for (i = 1, j = 0; i < numsSize; i++)
  40. if (nums[i] != nums[i-1])
  41. nums[++j] = nums[i];
  42. return (numsSize > 0 ? j+1 : j);
  43. }

发表评论

表情:
评论列表 (有 0 条评论,298人围观)

还没有评论,来说两句吧...

相关阅读